问题
It's my first time sending multipart requests and after digging here, I got even more confused so any help regarding the "correct" way will be very appriciated.
I have a function, that should get : file path and a String representation of JSON and send POST request to the server using multipart.
I'm not sure when to use the boundary and "multipart/form-data" content type, and the difference between addPart and addTextBody, and when (or why) it is always written 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..
Now I'm not sure how to continue, and how to write the file and the json string I saw this code:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
builder.addPart("text1", stringBody1);
builder.addPart("text2", stringBody2);
But I can't seem to understand how it is connected to my connection.
Can you please help?
回答1:
The sample HTML form:
<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 code for submiting the multipart form:
    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
    来源:https://stackoverflow.com/questions/29140570/how-to-send-multipart-post-request-using-httpurlconnection-in-java