Apache HttpClient - Multipart Upload

Using HttpClient, we can perform Multipart upload, i.e., we can upload larger objects in
smaller 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
Initiation of the upload
Uploading the object parts
Uploading the object parts
Completing the Multipart upload
Completing the Multipart upload
For the multipart upload using HttpClient, we need to follow the below steps −
Create a multipart builder.
Create a multipart builder.
Add desired parts to it.
Add desired parts to it.
Complete the build and obtain a multipart HttpEntity.
Complete the build and obtain a multipart HttpEntity.
Build request by setting the above muti-part entity.
Build request by setting the above muti-part entity.
Execute the request.
Execute the request.
Following are the steps to upload a multipart entity using the HttpClient library.
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 −
//Creating CloseableHttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();

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.
//Creating a File object
File file = new File("sample.txt");

//Creating the FileBody object
FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);

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

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

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.
//Adding text
entitybuilder.addTextBody("sample_text", "This is the text part of our file");
//Adding a file
entitybuilder.addBinaryBody("image", new File("logo.png"));

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.
//Building a single entity using the parts
HttpEntity mutiPartHttpEntity = entityBuilder.build(); 

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 Uri
to which you wanted to send the request it as a parameter.
//Building the post request object
RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post");

Set the above created multipart entity to the RequestBuilder using the setEntity() method of the RequestBuilder class.
//Setting the entity object to the RequestBuilder
reqbuilder.setEntity(mutiPartHttpEntity);

Build a HttpUriRequest request object using the build() method of the RequestBuilder class.
//Building the request
HttpUriRequest multipartRequest = reqbuilder.build();

Using the execute() method, execute the request built in the previous step (bypassing the request as a parameter to this method).
//Executing the request
HttpResponse httpresponse = httpclient.execute(multipartRequest);

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.
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

public class MultipartUploadExample {
 
   public static void main(String args[]) throws Exception{

      //Creating CloseableHttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();
 
      //Creating a file object
      File file = new File("sample.txt");

      //Creating the FileBody object
      FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);

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

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

      //Adding text
      entitybuilder.addTextBody("sample_text", "This is the text part of our file");

      //Adding a file
      entitybuilder.addBinaryBody("image", new File("logo.png"));

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

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

      //Set the entity object to the RequestBuilder
      reqbuilder.setEntity(mutiPartHttpEntity);

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

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

      //Printing the status and the contents of the response
      System.out.println(EntityUtils.toString(httpresponse.getEntity()));
      System.out.println(httpresponse.getStatusLine());
   }
} 
On executing, the above program generates the following output −
{
   "args": {},
   "data": "",
   "files": {
      "image": "data:application/octets66PohrH3IWNk1FzpohfdXPIfv9X3490FGcuXsHn9X0piCwomF/xdgADZ9GsfSyvLYAAAAAE
      lFTkSuQmCC"
   },
   "form": {
      "sample_text": "This is the text part of our file"
   },
   "headers": {
      "Accept-Encoding": "gzip,deflate",
      "Connection": "close",
      "Content-Length": "11104", 
      "Content-Type": "multipart/form-data;
      boundary=UFJbPHT7mTwpVq70LpZgCi5I2nvxd1g-I8Rt",
      "Host": "httpbin.org",
      "User-Agent": "Apache-HttpClient/4.5.6 (Java/1.8.0_91)"
   },
   "json": null,
   "origin": "117.216.245.180",
   "url": "http://httpbin.org/post"
}
HTTP/1.1 200 OK


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page