Skip to main content

Java Apache HttpClient: How to Send POST Requests

In this guide for The Java Web Scraping Playbook, we will look at how to make POST requests with the Java Apache HttpClient Version 5.

In this guide we will walk you through the most common ways of sending POST requests with Java Apache HttpClient:

Let's begin...


POST JSON Data Using Java Apache HttpClient

A common scenario for using POST requests is to send JSON data to an API endpoint, etc. Here we break down how to make POST requests this with Java Apache HttpClient.

Before you can make POST requests with Java Apache HttpClient, you need to import all the required classes from this library.

import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.apache.hc.core5.http.ContentType;
import java.util.concurrent.Future;

Now inside the main code, initialize requestUrl and jsonData variables.

String requestUrl = "https://httpbin.org/post";
String jsonData = "{ \"key\": \"value\" }";

After that create an instance of CloseableHttpClient using HttpsClients.createDefault method and set it to client variable. Call client.start method to initialize internal resources so that client is ready to make asynchronous http requests.

CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();

Next use SimpleRequestBuilder.post(requestUrl) to configure post request url. Then configure request body and its content-type by calling setBody method with jsonData and ContentType.APPLICATION_JSON respectively. To actually create your request object based on the supplied configurations, simply call build method.

SimpleHttpRequest request = SimpleRequestBuilder.post(requestUrl)
.setBody(jsonData, ContentType.APPLICATION_JSON)
.build();

Finally to send the post request, just use client.execute method.

Because client.execute is an asynchronous function, it doesn't immediately return response. It instead returns future object which is an instance of java Future<SimpleHttpResponse>. So you need to wait for the server to return response by calling future.get method.

Future<SimpleHttpResponse> future = client.execute(request, null);
SimpleHttpResponse response = future.get();
System.out.println("Response body: " + response.getBodyText());

To wrap up this section, here's the entire code for making POST requests with Java Apache HttpClient:

import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.apache.hc.core5.http.ContentType;
import java.util.concurrent.Future;

public class JsonPostRequest {
public static void main(String[] args) throws Exception {
String requestUrl = "https://httpbin.org/post";
String jsonData = "{\"key\": \"value\"}"; // replace with your JSON data

CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();

try {
SimpleHttpRequest request = SimpleRequestBuilder.post(requestUrl)
.setBody(jsonData, ContentType.APPLICATION_JSON)
.build();

Future<SimpleHttpResponse> future = client.execute(request, null);
SimpleHttpResponse response = future.get();
System.out.println("Response body: " + response.getBodyText());
} finally {
client.close();
}
}
}
Closing Http Client

Note that we call client.close method after our code finishes running (inside finally block). By doing so, we release system resources allocated by the client and prevent potential memory leaks.


POST Form Data Using Java Apache HttpClient

Another common use case for using POST requests is to send form data to an API endpoint. In this section, we'll see how we can make post request with the following formData.

String formData = "key1=value1&key2=value2";

To make form data POST requests with Apache HttpClient, simply call setBody method of request builder with formData as the first argument. The second argument is content type, which we set to ContentType.APPLICATION_FORM_URLENCODED so that the formData will indeed be picked up as form data.

SimpleHttpRequest request = SimpleRequestBuilder.post(requestUrl)
.setBody(formData, ContentType.APPLICATION_FORM_URLENCODED)
.build();

Here's the full code sample:

// imports have been left out here for sake of brevity

public class FormDataPostRequest {
public static void main(String[] args) throws Exception {
String requestUrl = "https://httpbin.org/post";
String formData = "key1=value1&key2=value2"; // replace with your form data

CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();

try {
SimpleHttpRequest request = SimpleRequestBuilder.post(requestUrl)
.setBody(formData, ContentType.APPLICATION_FORM_URLENCODED)
.build();

Future<SimpleHttpResponse> future = client.execute(request, null);
SimpleHttpResponse response = future.get();
System.out.println("Response body: " + response.getBodyText());
} finally {
client.close();
}
}
}

More Web Scraping Tutorials

So that's how you can send POST requests using Java Apache HttpClient.

If you would like to learn more about Web Scraping, then be sure to check out The Web Scraping Playbook.

Or check out one of our more in-depth guides: