How can I make a multipart/form-data POST request using Java?
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();
Upload File in form data using Java
This question is similar. But I believe the answer is changing your addBinary to addPart.
final HttpPost httppost = new HttpPost("https://host/upload");
httppost.addHeader("Authorization", "Bearer xxx");
httppost.addHeader("Accept", "application/json");
httppost.addHeader("Content-Type", "multipart/form-data");
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
final File file = new File("c:\\tmp\\myfile.pdf");
builder.addPart("file", new FileBody(file));
builder.addTextBody("type", "file");
final HttpEntity entity = builder.build();
httppost.setEntity(entity);
final HttpResponse response = httpclient.execute(httppost);
httpclient.close();
Related Topics
How to Handle JPA Unique Constraint Violations
How to Check Json in Response Body With Mockmvc
How to Convert Minutes to Hours and Minutes (Hh:Mm) in Java
Duplicate Entry Exception: Spring Hibernate/Jpa Cascade Save Many to One
Empty Check With String[] Array
How to Replace a Placeholder in a String With a Simpledateformat Pattern
Return Json Object from a Spring-Boot Rest Controller
Spring MVC Web Application: No Default Constructor Found
Using Streams to Convert a List of Objects into a String Obtained from the Tostring Method
Printing a Statement Only Once in a While Loop
Java Stream Collectors.Groupingby() Multiple Fields
Java.Lang.Illegalargumentexception: Not a Managed Type: Class
How to Increase the Java Heap Size Permanently
Getting Column Names from a JPA Native Query
Java Execution Pops a New Window and Immediately Disappears
Calculate the Number of Items Displayed by Recyclerview and Place in a Textview