Apache HttpClient POST HTTP Request Example

In this quick article, we will discuss step by step how to use Apache HttpClient 4.5 to make an HTTP POST request. The HTTP POST request method requests that the server accepts the entity enclosed in the request as a new subordinate of the web resource identified by the URI.
HttpClient supports out of the box all HTTP methods defined in the HTTP/1.1 specification: GETHEADPOSTPUTDELETETRACE, and OPTIONS. There is a specific class for each method type.: HttpGetHttpHeadHttpPostHttpPutHttpDeleteHttpTrace, and HttpOptions.
In this example, we will use HttpPost class to handle the POST HTTP method.
Check out Apache HttpClient GET HTTP Request Example

Using the Apache HttpClient - Add Dependency

The Apache HttpClient library allows handling HTTP requests. To use this library add a dependency to your Maven or Gradle build file. You find the latest version here: https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
We use maven to manage our dependencies and are using Apache HttpClient version 4.5. Add the following dependency to your project in order to make HTTP POST request method.
<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.5</version>
</dependency>

Development Steps

Let's create a step by step example to make an HTTP POST request using HttpClient.

1. Create instance of CloseableHttpClient using helper class HttpClients.

CloseableHttpClient httpclient = HttpClients.createDefault()
The HttpClients.createDefault() method creates CloseableHttpClient instance with default configuration.

2. Create a basic POST request

HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");

3. Add headers to Post HTTP Request

HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

3. Add JSON Data to Post request

String json = "{\r\n" + 
  "  \"firstName\": \"Ram\",\r\n" + 
  "  \"lastName\": \"Jadhav\",\r\n" + 
  "  \"emailId\": \"ramesh1234@gmail.com\",\r\n" + 
  "  \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" + 
  "  \"createdBy\": \"Ramesh\",\r\n" + 
  "  \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" + 
  "  \"updatedby\": \"Ramesh\"\r\n" + 
  "}";
StringEntity stringEntity = new StringEntity(json);
httpPost.setEntity(stringEntity);

4. Create a custom response handler

ResponseHandler < String > responseHandler = response - > {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    } else {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
};

5. Send basic POST request via execute() Method

String responseBody = httpclient.execute(httpPost, responseHandler);

HttpClient HTTP POST Request Method Example

Let's discuss how to use HttpClient in real-time projects. Consider we have deployed Spring boot Restful CRUD APIs. Check out this article - Spring Boot 2 + hibernate 5 + CRUD REST API Tutorial.
In the following example, we send a resource to http://localhost:8080/api/v1/users. This resource accepts the request JSON, process it and store it into a database. This service also returns a response with a resource. In this example, we are using Java 7 try-with-resources to automatically handle the closing of the ClosableHttpClient and we are also using Java 8 lambdas for the ResponseHandler.
package com.javadevelopersguide.httpclient.examples;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates the use of {@link HttpPost} request method.
 * @author Ramesh Fadatare
 */
public class HttpPostRequestMethodExample {

    public static void main(String[] args) throws IOException {
        postUser();
    }

    public static void postUser() throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            String json = "{\r\n" +
                "  \"firstName\": \"Ram\",\r\n" +
                "  \"lastName\": \"Jadhav\",\r\n" +
                "  \"emailId\": \"ramesh1234@gmail.com\",\r\n" +
                "  \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" +
                "  \"createdBy\": \"Ramesh\",\r\n" +
                "  \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" +
                "  \"updatedby\": \"Ramesh\"\r\n" +
                "}";
            StringEntity stringEntity = new StringEntity(json);
            httpPost.setEntity(stringEntity);

            System.out.println("Executing request " + httpPost.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpPost, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

Output

Executing request POST http://localhost:8080/api/v1/users HTTP/1.1
----------------------------------------
{"id":37,"firstName":"Ram","lastName":"Jadhav","emailId":"ramesh1234@gmail.com",
"createdAt":"2018-10-29T09:37:09.821+0000","createdBy":"Ramesh","updatedAt":"2018-10-29T09:37:09.821+0000",
"updatedby":"Ramesh"}

More Examples

In the following example, we post data to the resource http://httpbin.org/post. This resources acknowledges the data and returns a JSON object which we’ll simply print to the console. 
package com.javadevelopersguide.httpclient.examples;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates the use of {@link HttpPost} request method.
 */
public class HttpPostRequestMethodExample {

    public static void main(String[] args) throws IOException {
        post();
    }
    public static void post() throws IOException {

        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost("http://httpbin.org/post");
            httpPost.setEntity(new StringEntity("Hello, World"));

            System.out.println("Executing request " + httpPost.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpPost, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

Output

Executing request POST http://httpbin.org/post HTTP/1.1
----------------------------------------
{
  "args": {}, 
  "data": "Hello, World", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "gzip,deflate", 
    "Connection": "close", 
    "Content-Length": "12", 
    "Content-Type": "text/plain; charset=ISO-8859-1", 
    "Host": "httpbin.org", 
    "User-Agent": "Apache-HttpClient/4.5 (Java/1.8.0_172)"
  }, 
  "json": null, 
  "origin": "49.35.12.218", 
  "url": "http://httpbin.org/post"
}

References

Comments