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.
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:
Below is the original snippet of code with deprecated HttpClient 4.0 API:
If size of the JARs matters (e.g. in case of applet), one can also directly use httpmime with java.net.HttpURLConnection instead of HttpClient.
Code:
Dependency in pom.xml:
I found this sample in Apache's Quickstart Guide. It's for version 4.5:
Use this code to upload images or any other files to the server using post in multipart.
it requires below files to upload.
libraries are
httpclient-4.1.2.jar,
httpcore-4.1.2.jar,
httpmime-4.1.2.jar,
httpclient-cache-4.1.2.jar,
commons-codec.jar
andcommons-logging-1.1.1.jar
to be in classpath.You can also use REST Assured which builds on HTTP Client. It's very simple:
httpcomponents-client-4.0.1
worked for me. However, I had to add the external jarapache-mime4j-0.6.jar
(org.apache.james.mime4j) otherwisereqEntity.addPart("bin", bin);
would not compile. Now it's working like charm.