Using HttpClient, we can perform Multipart upload, i.e., we can upload larger objects insmaller parts. In this chapter, we demonstrate the multipart upload in HTTP client by uploading a simple text file.

In general, any multipart upload contains three parts.

  • Initiation of the upload

  • Uploading the object parts

  • Completing the Multipart upload

For the multipart upload using HttpClient, we need to follow the below steps −

  • Create a multipart builder.

  • Add desired parts to it.

  • Complete the build and obtain a multipart HttpEntity.

  • Build request by setting the above muti-part entity.

  • Execute the request.

Following are the steps to upload a multipart entity using the HttpClient library.

Step 1 - Create an HttpClient object

The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object −

  1. //Creating CloseableHttpClient object
  2. CloseableHttpClient httpclient = HttpClients.createDefault();

Step 2 - Create a FileBody object

FileBody class represents the binary body part backed by a file. Instantiate this class by passing a File object and a ContentType object representing the type of the content.

  1. //Creating a File object
  2. File file = new File("sample.txt");
  3.  
  4. //Creating the FileBody object
  5. FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);

Step 3 - Create a MultipartEntityBuilder

The MultipartEntityBuilder class is used to build the multi-part HttpEntity object. Create its object using the create() method (of the same class).

  1. //Creating the MultipartEntityBuilder
  2. MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();

Step 4 - Set the mode

A MultipartEntityBuilder has three modes: STRICT, RFC6532, and BROWSER_COMPATIBLE. Set it to the desired mode using the setMode() method.

  1. //Setting the mode
  2. entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

Step 5 - Add various the desired parts

Using the methods addTextBody(), addPart() and, addBinaryBody(), you can add simple text, files, streams, and other objects to a MultipartBuilder. Add the desired contents using these methods.

  1. //Adding text
  2. entitybuilder.addTextBody("sample_text", "This is the text part of our file");
  3. //Adding a file
  4. entitybuilder.addBinaryBody("image", new File("logo.png"));

Step 6 - Building single entity

You can build all these parts to a single entity using the build() method of the MultipartEntityBuilder class. Using this method, build all the parts into a single HttpEntity.

  1. //Building a single entity using the parts
  2. HttpEntity mutiPartHttpEntity = entityBuilder.build();

Step 7 - Create a RequestBuilder object

The class RequestBuilder is used to build request by adding parameters to it. If the request is of type PUT or POST, it adds the parameters to the request as URL encoded entity.

Create a RequestBuilder object (of type POST) using the post() method. And pass the Urito which you wanted to send the request it as a parameter.

  1. //Building the post request object
  2. RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post");

Step 8 - Set the entity object to the RequestBuilder

Set the above created multipart entity to the RequestBuilder using the setEntity() method of the RequestBuilder class.

  1. //Setting the entity object to the RequestBuilder
  2. reqbuilder.setEntity(mutiPartHttpEntity);

Step 9 - Build the HttpUriRequest

Build a HttpUriRequest request object using the build() method of the RequestBuilder class.

  1. //Building the request
  2. HttpUriRequest multipartRequest = reqbuilder.build();

Step 10 - Execute the request

Using the execute() method, execute the request built in the previous step (bypassing the request as a parameter to this method).

  1. //Executing the request
  2. HttpResponse httpresponse = httpclient.execute(multipartRequest);

Example

Following example demonstrates how to send a multipart request using the HttpClient library. In this example, we are trying to send a multipart request backed by a file.

  1. import org.apache.http.HttpEntity;
  2. import org.apache.http.HttpResponse;
  3. import org.apache.http.client.methods.HttpUriRequest;
  4. import org.apache.http.client.methods.RequestBuilder;
  5. import org.apache.http.entity.ContentType;
  6. import org.apache.http.entity.mime.HttpMultipartMode;
  7. import org.apache.http.entity.mime.MultipartEntityBuilder;
  8. import org.apache.http.entity.mime.content.FileBody;
  9. import org.apache.http.impl.client.CloseableHttpClient;
  10. import org.apache.http.impl.client.HttpClients;
  11. import org.apache.http.util.EntityUtils;
  12. import java.io.File;
  13. import java.io.IOException;
  14. import java.net.URISyntaxException;
  15.  
  16. public class MultipartUploadExample {
  17.  
  18. public static void main(String args[]) throws Exception{
  19.  
  20. //Creating CloseableHttpClient object
  21. CloseableHttpClient httpclient = HttpClients.createDefault();
  22.  
  23. //Creating a file object
  24. File file = new File("sample.txt");
  25.  
  26. //Creating the FileBody object
  27. FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);
  28.  
  29. //Creating the MultipartEntityBuilder
  30. MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
  31.  
  32. //Setting the mode
  33. entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  34.  
  35. //Adding text
  36. entitybuilder.addTextBody("sample_text", "This is the text part of our file");
  37.  
  38. //Adding a file
  39. entitybuilder.addBinaryBody("image", new File("logo.png"));
  40.  
  41. //Building a single entity using the parts
  42. HttpEntity mutiPartHttpEntity = entitybuilder.build();
  43.  
  44. //Building the RequestBuilder request object
  45. RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post");
  46.  
  47. //Set the entity object to the RequestBuilder
  48. reqbuilder.setEntity(mutiPartHttpEntity);
  49.  
  50. //Building the request
  51. HttpUriRequest multipartRequest = reqbuilder.build();
  52.  
  53. //Executing the request
  54. HttpResponse httpresponse = httpclient.execute(multipartRequest);
  55.  
  56. //Printing the status and the contents of the response
  57. System.out.println(EntityUtils.toString(httpresponse.getEntity()));
  58. System.out.println(httpresponse.getStatusLine());
  59. }
  60. }

Output

On executing, the above program generates the following output −

  1. {
  2. "args": {},
  3. "data": "",
  4. "files": {
  5. "image": "data:application/octets66PohrH3IWNk1FzpohfdXPIfv9X3490FGcuXsHn9X0piCwomF/xdgADZ9GsfSyvLYAAAAAE
  6. lFTkSuQmCC"
  7. },
  8. "form": {
  9. "sample_text": "This is the text part of our file"
  10. },
  11. "headers": {
  12. "Accept-Encoding": "gzip,deflate",
  13. "Connection": "close",
  14. "Content-Length": "11104",
  15. "Content-Type": "multipart/form-data;
  16. boundary=UFJbPHT7mTwpVq70LpZgCi5I2nvxd1g-I8Rt",
  17. "Host": "httpbin.org",
  18. "User-Agent": "Apache-HttpClient/4.5.6 (Java/1.8.0_91)"
  19. },
  20. "json": null,
  21. "origin": "117.216.245.180",
  22. "url": "http://httpbin.org/post"
  23. }
  24. HTTP/1.1 200 OK