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

use*_*966 6 java http multipart http-post

这是我第一次发送多部分请求,在这里挖掘之后,我变得更加困惑,所以任何有关"正确"方式的帮助都会非常受欢迎.

我有一个函数,应该得到:文件路径和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..
Run Code Online (Sandbox Code Playgroud)

现在我不知道如何继续,以及如何编写文件和json字符串我看到这段代码:

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
builder.addPart("text1", stringBody1);
builder.addPart("text2", stringBody2);
Run Code Online (Sandbox Code Playgroud)

但我似乎无法理解它与我的关系connection.

你能帮忙吗?

Bec*_*ang 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>
Run Code Online (Sandbox Code Playgroud)

用于提交多部分表单的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
Run Code Online (Sandbox Code Playgroud)