- Multipart Upload
- Custom SSL Context
- Multiple Threads
- Cookies Management
- Form-Based Login
- Proxy Authentication
- Using Proxy
- User Authentication
- Interceptors
- Aborting a Request
- Closing Connection
- Response Handlers
- Http Post Request
- Http Get Request
- Environment Setup
- Overview
- Home
Apache HttpClient Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Apache HttpCpent - Multipart Upload
Using HttpCpent, 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 cpent 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 HttpCpent, 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 HttpCpent pbrary.
Step 1 - Create an HttpCpent object
The createDefault() method of the HttpCpents class returns an object of the class CloseableHttpCpent, which is the base implementation of the HttpCpent interface. Using this method, create an HttpCpent object −
//Creating CloseableHttpCpent object CloseableHttpCpent httpcpent = HttpCpents.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.
//Creating a File object File file = new File("sample.txt"); //Creating the FileBody object 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).
//Creating the MultipartEntityBuilder 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.
//Setting the mode 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.
//Adding text entitybuilder.addTextBody("sample_text", "This is the text part of our file"); //Adding a file 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.
//Building a single entity using the parts 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 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");
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.
//Setting the entity object to the RequestBuilder reqbuilder.setEntity(mutiPartHttpEntity);
Step 9 - Build the HttpUriRequest
Build a HttpUriRequest request object using the build() method of the RequestBuilder class.
//Building the request 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).
//Executing the request HttpResponse httpresponse = httpcpent.execute(multipartRequest);
Example
Following example demonstrates how to send a multipart request using the HttpCpent pbrary. 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.cpent.methods.HttpUriRequest; import org.apache.http.cpent.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.cpent.CloseableHttpCpent; import org.apache.http.impl.cpent.HttpCpents; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; pubpc class MultipartUploadExample { pubpc static void main(String args[]) throws Exception{ //Creating CloseableHttpCpent object CloseableHttpCpent httpcpent = HttpCpents.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 = httpcpent.execute(multipartRequest); //Printing the status and the contents of the response System.out.println(EntityUtils.toString(httpresponse.getEntity())); System.out.println(httpresponse.getStatusLine()); } }
Output
On executing, the above program generates the following output −
{ "args": {}, "data": "", "files": { "image": "data:apppcation/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-HttpCpent/4.5.6 (Java/1.8.0_91)" }, "json": null, "origin": "117.216.245.180", "url": "http://httpbin.org/post" } HTTP/1.1 200 OKAdvertisements