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

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</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