Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send multipart POST request using HttpURLConnection in java?

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?

like image 342
user1386966 Avatar asked Mar 19 '15 09:03

user1386966


1 Answers

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
like image 60
Beck Yang Avatar answered Oct 11 '22 13:10

Beck Yang