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

时间:2015-03-19 09:09:02

标签: java http http-post multipart

这是我第一次发送多部分请求,在这里挖掘之后,我更加困惑,所以任何关于"正确"的帮助方式将非常适合。

我有一个函数,应该得到:文件路径和JSON的String表示,并使用multipart向服务器发送POST请求。

我不确定何时使用boundary"multipart/form-data"内容类型,以及addPartaddTextBody之间的差异,以及何时(或为什么)它总是写成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);

但我似乎无法理解它与connection的关联方式。

你能帮忙吗?

1 个答案:

答案 0 :(得分:3)

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