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>

How do I send POST request with a JSON body using the HttpClient?

The following code snippet show you how to send POST request with a JSON body using HttpClient. The payload in this example is a user information containing id, first_name and a last_name. We placed the payload in an object called StringEntity and also set its content type to ContentType.APPLICATION_FORM_URLENCODED.

On the other end called by this post request, data can be read for instance in a Java Servlet using the HttpServletRequest.getParameter() method. For example to read the JSON body send below we can call request.getParameter("data"). Which will give us the payload send using the HttpClient Post request.

Let’s jump into the code snippet below:

package org.kodejava.example.httpclient;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

public class HttpPostJsonExample {
    public static void main(String[] args) throws Exception {
        String payload = "data={" +
                "\"username\": \"admin\", " +
                "\"first_name\": \"System\", " +
                "\"last_name\": \"Administrator\"" +
                "}";
        StringEntity entity = new StringEntity(payload,
                ContentType.APPLICATION_FORM_URLENCODED);

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost request = new HttpPost("http://localhost:8080/register");
        request.setEntity(entity);

        HttpResponse response = httpClient.execute(request);
        System.out.println(response.getStatusLine().getStatusCode());
    }
}

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>

How do I send an HTTP POST request?

The following code snippet will show you how to send an HTTP post request using the Apache HttpComponents. We will send a post request to http://localhost:8080/register, with some parameters to the request using the NameValuePair object.

To pass this parameters to the HTTP post request we create an instance of UrlEncodedFormEntity and pass a list of NameValuePair as the arguments. And before executing the request we set this entity object to the HttpPost.setEntity() method.

Let’s see the code below:

package org.kodejava.example.httpclient;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HttpPostExample {
    public static void main(String[] args) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("http://localhost:8080/register");

        // Create some NameValuePair for HttpPost parameters
        List<NameValuePair> arguments = new ArrayList<>(3);
        arguments.add(new BasicNameValuePair("username", "admin"));
        arguments.add(new BasicNameValuePair("firstName", "System"));
        arguments.add(new BasicNameValuePair("lastName", "Administrator"));

        try {
            post.setEntity(new UrlEncodedFormEntity(arguments));
            HttpResponse response = client.execute(post);

            // Print out the response message
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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>

How do I get entity ContentType in HttpClient?

This code snippet show you how to get the content type of a result of executing an Http Get request. The ContentType can be obtained by using ContentType.getOrDefault() method and passing an HttpEntity as the arguments. The HttpEntity can be obtained from the HttpResponse object.

From the ContentType object we can get the mime-type by calling the getMimeType() method. This method will return a string value. To get the charset we can call the getCharset() method which will return a java.nio.charset.Charset object.

package org.kodejava.example.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;
import java.nio.charset.Charset;

public class EntityContentType {
    public static void main(String[] args) {
        EntityContentType demo = new EntityContentType();
        demo.getContentType("http://www.google.com");
        demo.getContentType("http://www.google.com/images/srpr/logo3w.png");
    }

    public void getContentType(String url) {
        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            showContentType(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void showContentType(HttpEntity entity) {
        ContentType contentType = ContentType.getOrDefault(entity);
        String mimeType = contentType.getMimeType();
        Charset charset = contentType.getCharset();

        System.out.println("MimeType = " + mimeType);
        System.out.println("Charset  = " + charset);
    }
}

The output of our code snippet are:

MimeType = text/html
Charset  = ISO-8859-1
MimeType = image/png
Charset  = null

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.2</version>
</dependency>

How do I get HTTP response body as a string?

This example show you how to get HTTP response body as a string when using the Apache HttpComponents library. To get the response body as a string we can use the EntityUtils.toString() method. This method read the content of an HttpEntity object content and return it as a string. The content will be converted using the character set from the entity object.

Let’s see the code snippet below:

package org.kodejava.example.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class EntityAsString {
    public static void main(String[] args) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet("https://kodejava.org");

        try {
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();

            // Read the contents of an entity and return it as a String.
            String content = EntityUtils.toString(entity);
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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>