Execute an HTTP POST Request in Java

In the previous lesson, we covered a HTTP GET request. And in this tutorial, you will learn how to execute an HTTP POST request in Java.

We use the HTTP POST method to send data to the server.

If you are learning how to send HTTP methods in Java, then you might also be interested to learn in the following tutorials:

To execute an HTTP request in Java, we need to have an HTTP client as a dependency.

In this tutorial, we will cover the HTTP POST request using the Apache HttpClient

First, we need to add Maven dependency:

<dependency>
    <groupid>org.apache.httpcomponents</groupid>
    <artifactid>httpclient</artifactid>
    <version>4.5.13</version>
</dependency>


Find other versions here → Apache HTTP Client. If you are not using Maven, you can download JAR from the location above.

Execute a POST request in Java using the Apache HTTP Client

Below is a simple example of executing a POST request:

import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

public class Test {

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

    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
      HttpPost httpPost = new HttpPost("https://jsonplaceholder.typicode.com/posts");
      
      // specify the POST body to send to the server as part of the request
      httpPost.setEntity(new StringEntity("{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"));

      System.out.println("Executing POST request...");
      HttpResponse response = httpclient.execute(httpPost);

      System.out.println("Status code: " + response.getStatusLine().getStatusCode());
      
      String responseBody = new BasicResponseHandler().handleResponse(response);

      System.out.println("Response: " + responseBody);
    }
  }
}
Output: Executing POST request… Status code: 201 Response: { “id”: 101 }
 
We used the try-with-resources to create an HttpClient. That means we don’t have to close it after executing the request. The try-with-resources statement ensures that each resource is closed at the end of the statement.
 
We also used the BasicResponseHandler to retrive the response body and response.getStatusLine().getStatusCode() to retrive the response status code.

Execute a POST request with headers

We can also add HTTP headers to the request, like in the following example:

import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;

import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;

import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

public class Test {

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

    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
      HttpUriRequest request = RequestBuilder.post()
              .setUri("https://jsonplaceholder.typicode.com/posts")
              .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
              .setHeader("Authorization", "Bearer 123token")
              // add request body
              .setEntity(new StringEntity("{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"))
              .build();

      System.out.println("Executing POST request... ");
      HttpResponse response = httpclient.execute(request);

      System.out.println("Status code: " + response.getStatusLine().getStatusCode());

      String responseString = new BasicResponseHandler().handleResponse(response);

      System.out.println("Response: " + responseString);

    }
  }
}
Output: Executing POST request… Status code: 201 Response: { “id”: 101 }
 
We used the RequestBuilder class to build the request with all the required data (URL, headers, request body).
 
I hope this tutorial was helpful to you. If you are working with HttpClient then you might also be interested to learn how to configure HttpClient to accept all SSL certificates
 
Happy learning!

Leave a Reply

Your email address will not be published. Required fields are marked *