如何使用HttpURLConnection在Java中发送多部分POST请求?

6
这是我的第一次发送多部分请求,经过调查后,我更加困惑了,因此任何有关“正确”方法的帮助都将非常感激。
我有一个函数,应该获取:文件路径和JSON的字符串表示形式,并使用multipart发送POST请求到服务器。
我不确定何时使用boundary和“multipart/form-data”内容类型,以及addPart和addTextBody之间的区别,还有何时(或为什么)总是写入Content-Disposition: form-data; name =。
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);

但是我似乎不理解它与我的连接有什么关系。

你能帮忙吗?


这正是我的问题。我找不到有关使用MultipartEntityBuilder和HttpURLConnection的详细信息。 - Bruno Tavares
1个回答

5

样例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>

提交多部分表单的Java代码:

    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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接