How can I make a multipart/form-data POST request using Java?

lutz picture lutz · Sep 4, 2009 · Viewed 276.7k times · Source

In the days of version 3.x of Apache Commons HttpClient, making a multipart/form-data POST request was possible (an example from 2004). Unfortunately this is no longer possible in version 4.0 of HttpClient.

For our core activity "HTTP", multipart is somewhat out of scope. We'd love to use multipart code maintained by some other project for which it is in scope, but I'm not aware of any. We tried to move the multipart code to commons-codec a few years ago, but I didn't take off there. Oleg recently mentioned another project that has multipart parsing code and might be interested in our multipart formatting code. I don't know the current status on that. (http://www.nabble.com/multipart-form-data-in-4.0-td14224819.html)

Is anybody aware of any Java library that allows me to write an HTTP client that can make a multipart/form-data POST request?

Background: I want to use the Remote API of Zoho Writer.

Answer

ZZ Coder picture ZZ Coder · Sep 4, 2009

We use HttpClient 4.x to make multipart file post.

UPDATE: As of HttpClient 4.3, some classes have been deprecated. Here is the code with new API:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);

// This attaches the file to the POST:
File f = new File("[/path/to/upload]");
builder.addBinaryBody(
    "file",
    new FileInputStream(f),
    ContentType.APPLICATION_OCTET_STREAM,
    f.getName()
);

HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();

Below is the original snippet of code with deprecated HttpClient 4.0 API:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);

FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();