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 possi
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. Now it's working like charm.
You can also use REST Assured which builds on HTTP Client. It's very simple:
given().multiPart(new File("/somedir/file.bin")).when().post("/fileUpload");
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>
Here's a solution that does not require any libraries.
This routine transmits every file in the directory d:/data/mpf10
to urlToConnect
String boundary = Long.toHexString(System.currentTimeMillis());
URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
File dir = new File("d:/data/mpf10");
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
continue;
}
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"" + file.getName() + "\"; filename=\"" + file.getName() + "\"");
writer.println("Content-Type: text/plain; charset=UTF-8");
writer.println();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
writer.println(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
}
writer.println("--" + boundary + "--");
} finally {
if (writer != null) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
// Handle response
My code post multipartFile to server.
public static HttpResponse doPost(
String host,
String path,
String method,
MultipartFile multipartFile
) throws IOException
{
HttpClient httpClient = wrapClient(host);
HttpPost httpPost = new HttpPost(buildUrl(host, path));
if (multipartFile != null) {
HttpEntity httpEntity;
ContentBody contentBody;
contentBody = new ByteArrayBody(multipartFile.getBytes(), multipartFile.getOriginalFilename());
httpEntity = MultipartEntityBuilder.create()
.addPart("nameOfMultipartFile", contentBody)
.build();
httpPost.setEntity(httpEntity);
}
return httpClient.execute(httpPost);
}
I found this sample in Apache's Quickstart Guide. It's for version 4.5:
/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}