Apache HttpClient POST request

In this article, we will explore how to execute an HTTP POST request using Apache HttpClient library with example programs.
Setup
For using HttpClient library, you need to add it to your project as per the build tool using below dependency

// GRADLE
implementation 'org.apache.httpcomponents:httpclient:4.5.14'

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

If you are not using any build tool, then directly add its jar file to the classpath.

Note: Post version 4.5.14, httpclient has moved to a different artifact.
So, if you have to use later dependency, then use below

// MAVEN
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.2.1</version>
</dependency>

// GRADLE
implementation 'org.apache.httpcomponents.client5:httpclient5:5.2.1'

To test our program, we need an endpoint URL.
For this article, we will be using a fake web service URL https://jsonplaceholder.typicode.com/posts, along with a body containing the fields of post and their values.

Below are field names and their arbitrary values

"title": "foo",
"body": "bar",
"userId": "1",
"id": 101

If the request is successful, it returns the request body as it is.

Steps
Following are the steps required to execute a POST request using Apache HttpClient.

1. Create a client.
A client is used to send HTTP requests to a URL. This URL is called endpoint URL or simply endpoint.

A client object in HttpClient is created using below syntax

CloseableHttpClient client = HttpClients.createDefault();

At some places, you will also find below code that creates an instance of HttpClient.

CloseableHttpClient client = HttpClientBuilder.create().build();

Both are the same since createDefault() internally calls the same code.
2. Create a request
To execute a request in HttpClient, we need an object of HttpUriRequest.
This is an interface which is implemented by classes that represent HTTP request types such as HttpGet and HttpPost for GET and POST requests respectively.

Since this article shows a POST request, we need to create an object of HttpPost as below

HttpPost request = new HttpPost(
                      "https://jsonplaceholder.typicode.com/posts");

Constructor of HttpPost accepts the endpoint URL at which the data will be posted.

3. Add request body
Request body implies that data that we need to send along with the request.
This data is generally persisted to the database at the backend server. There are two ways to send data in POST request with Apache HttpClient.

A. As key-value pairs
Apache HttpClient allows you to add POST request data in the form of key and value pairs.
HttpPost class has a setEntity() method where you can add a list of parameters to send in request body.
Parameters are added as objects of BasicNameValuePair class, which implements NameValuePair. Example,

List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("title", "foo"));

B. As json
Instead of adding individual key-value pairs which becomes tedious when the body is large, you can directly provide a json string as request body to the setEntity() method.

Examples of both these methods are given in the next section.

4. Execute request
Once we have a client and a request, it can directly be executed using execute() method of client.

execute() accepts an object of HttpUriRequest, which we created in the last step and returns the response returned by the URL as an object of CloseableHttpResponse as below

CloseableHttpResponse response = client.execute(get);

5. Reading response
CloseableHttpResponse contains a getEntity() method which returns an HttpEntity object, that contains the actual response.

HttpEntity has a getContent() method which returns a java InputStream containing the response.
This Inputstream can be used to read the response using BufferedReader or can be directly converted to a string.

HttpClient POST example
Below is a complete example of executing a POST request with HttpClient using the steps outlined above.
This method uses key-value pairs to add body to the request

// create client
CloseableHttpClient client = HttpClients.createDefault();
// create request object
HttpPost post = new HttpPost(
                   "https://jsonplaceholder.typicode.com/posts");
try {
  // create key-value pairs
  List<NameValuePair> params = new ArrayList<>();
  params.add(new BasicNameValuePair("title", "foo"));
  params.add(new BasicNameValuePair("body", "bar"));
  params.add(new BasicNameValuePair("userId", "1"));
  // add to request
  post.setEntity(new UrlEncodedFormEntity(params));
  // get response
  CloseableHttpResponse response = client.execute(post);
  // inputstream to bufferedread
  BufferedReader br = new BufferedReader(
                          new InputStreamReader(
          response.getEntity().getContent()));
  String line = null;
  // read response
  while( (line = br.readLine())!=null) {
    System.out.println(line);
  }
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Below is the response received

{
“title”: “foo”,
“body”: “bar”,
“userId:” “1”,
“id”: “101”
}

Note that setEntity() accepts a parameter of type HttpEntity.
To provide the body as key-value pairs, we provide it an object of UrlEncodedFormEntity, which accepts a list of NameValuePair objects.
UrlEncodedFormEntity converts the list of body parameters as a single String object.
HttpClient json POST
Below code directly adds a json string to the request body. This is useful when the number of body parameters is large or you have an already populated object which can be converted to a string.

// create client 
CloseableHttpClient client = HttpClients.createDefault(); 
// create request object 
HttpPost post = new HttpPost(
                    "https://jsonplaceholder.typicode.com/posts"); 
try {
 // define json body
 String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
 // add to request
 post.setEntity(new StringEntity(json)); 
 post.setHeader("Content-Type", "application/json");
 // get response 
 CloseableHttpResponse response = client.execute(post); 
 // inputstream to bufferedread 
 BufferedReader br = new BufferedReader( 
                        new InputStreamReader(
                           response.getEntity().getContent())); 
 String line = null; 
 // read response 
 while( (line = br.readLine())!=null) { 
   System.out.println(line); 
 } 
} catch (ClientProtocolException e) { 
  e.printStackTrace(); 
} catch (IOException e) {
  e.printStackTrace(); 
}

Note that here, we are passing an object of StringEntity to setEntity() method.
This is because setEntity() accepts an object of type HttpEntity, an interface and StringEntity implements it.

Also, note that in this request, we are also setting Content-Type header to “application/json” to inform the server that the request will be containing json data.

Hope the article was useful in explaining how Apache HttpClient can be used to send HTTP POST request containing a body.
This body can be in key-value pairs or in json.