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"). This will give us the payload sent using the HttpClient Post request.

Let’s jump into the code snippet below:

package org.kodejava.apache.http;

import org.apache.http.HttpResponse;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;

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

        try (CloseableHttpClient 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());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version>
</dependency>

Maven Central

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 https://httpbin.org/post, with some parameters to the request using the NameValuePair object.

To pass these 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.apache.http;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
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) {
        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            HttpPost post = new HttpPost("https://httpbin.org/post");

            // 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"));


            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

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version>
</dependency>

Maven Central