如何在java中使用HttpURLConnection发送多部分POST请求?
这是我第一次发送多部分请求,在这里挖掘之后,我变得更加困惑,因此任何关于“正确”方式的帮助都将非常宝贵 我有一个函数,它应该获取:file path和JSON的字符串表示形式,并使用multipart向服务器发送POST请求 我不确定何时使用如何在java中使用HttpURLConnection发送多部分POST请求?,java,http,http-post,multipart,Java,Http,Http Post,Multipart,这是我第一次发送多部分请求,在这里挖掘之后,我变得更加困惑,因此任何关于“正确”方式的帮助都将非常宝贵 我有一个函数,它应该获取:file path和JSON的字符串表示形式,并使用multipart向服务器发送POST请求 我不确定何时使用边界和“多部分/表单数据”内容类型,以及添加部分和添加文本体之间的区别,以及何时(或为什么)总是写入内容配置:表单数据;名称=\ public String foo(String filePath, String jsonRep, Proxy proxy)
边界
和“多部分/表单数据”
内容类型,以及添加部分
和添加文本体
之间的区别,以及何时(或为什么)总是写入内容配置:表单数据;名称=\
public String foo(String filePath, String jsonRep, Proxy proxy)
{
File f = new File(filePath);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection(proxy);
connection.setRequestProperty("Content-Type", "multipart/form-data"); // How should I generate boundary? Should it be added here?
if (myMethod == "POST")
{
connection.getOutputStream().write( ? Both the json string and the file bytes?? );
}
.... checking there is no error code etc..
return ReadResponse(connection) // read input stream..
现在我不确定如何继续,以及如何编写文件和json字符串
我看到了这个代码:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
builder.addPart("text1", stringBody1);
builder.addPart("text2", stringBody2);
但我似乎无法理解它是如何连接到我的连接的
您能帮忙吗?示例HTML表单:
<form method="post" action="http://127.0.0.1/app" enctype="multipart/form-data">
<input type="text" name="foo" value="bar"><br>
<input type="file" name="bin"><br>
<input type="submit" value="test">
</form>
这正是我的问题所在。我找不到关于使用MultipartEntityBuilder和HttpURLConnection的更多信息。
MultipartEntityBuilder mb = MultipartEntityBuilder.create();//org.apache.http.entity.mime
mb.addTextBody("foo", "bar");
mb.addBinaryBody("bin", new File("testFilePath"));
org.apache.http.HttpEntity e = mb.build();
URLConnection conn = new URL("http://127.0.0.1:8080/app").openConnection();
conn.setDoOutput(true);
conn.addRequestProperty(e.getContentType().getName(), e.getContentType().getValue());//header "Content-Type"...
conn.addRequestProperty("Content-Length", String.valueOf(e.getContentLength()));
OutputStream fout = conn.getOutputStream();
e.writeTo(fout);//write multi part data...
fout.close();
conn.getInputStream().close();//output of remote url