views:

3378

answers:

4

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.

+4  A: 

We use HttpClient 4.0 to make multipart file post. Here is a snippet of relevant code,

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();

This was done with a Beta version of HttpClient 4.0 a few years ago but I doubt these functions would be removed.

ZZ Coder
Ah, the multipart stuff has been moved to org.apache.httpcomponents-httpmime-4.0! Could be mentioned somewhere :/
A: 

hi

maybe this will help http://forums.sun.com/thread.jspa?forumID=31&threadID=451245

A: 

Hi

httpcomponents-client-4.0.1 worked for me. However I had to add the external jar apache-mime4j-0.6.jar (org.apache.james.mime4j) otherwise

reqEntity.addPart("bin", bin);

would not compile. It is running fine.

Bob Yoplait
+1  A: 

These are the Maven dependencies I have.

Java Code:

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

FileBody uploadFilePart = new FileBody(uploadFile);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("upload-file", uploadFilePart);
httpPost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httpPost);

Maven Dependencies in pom.xml:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.0.1</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.0.1</version>
  <scope>compile</scope>
</dependency>
Jaco van Niekerk