How do I do multipart upload using HttpClient?

This example demonstrates how to do multipart upload using the Apache HttpClient library. In this example we upload a single file. We start by creating an object of the file to be uploaded. The FileBody represent the binary body part of the file.

Next, prepare the HttpEntity object by create an instance of MultipartEntityBuilder. Add parts to this object, in this case we add the fileBody. We can add multiple part to this object as the name says. It can be string, file, etc as we do in a normal web form.

The build() method of the builder object finalize the entity creation and return us the HttpEntity object. To send / upload to server we create an HttpPost request and set the entity to be posted. Finally the execute() method of the HttpClient object send the multipart object to server.

package org.kodejava.example.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
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.HttpClientBuilder;

import java.io.File;
import java.io.IOException;

public class HttpPostMultipartExample {
    public static void main(String[] args) {
        File file = new File("data.zip");
        FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("file", fileBody);
        HttpEntity entity = builder.build();

        HttpPost request = new HttpPost("http://localhost:8080/upload");
        request.setEntity(entity);

        HttpClient client = HttpClientBuilder.create().build();
        try {
            client.execute(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

To receive the file on the server you can take a look at the servlet code in the following example: How do I create a web based file upload?.

Maven Dependencies

<!-- http://repo1.maven.org/maven2/org/apache/httpcomponents/httpclient/4.5.3/httpclient-4.5.3.jar -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>
<!-- http://repo1.maven.org/maven2/org/apache/httpcomponents/httpmime/4.5.3/httpmime-4.5.3.jar -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.3</version>
</dependency>

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply