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, 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.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("");

            // 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
        } catch (IOException e) {

Maven Dependencies


Maven Central



  1. You can try the code snippet below to send JSON message.

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost request = new HttpPost("http://localhost:8080/servlet");
    String payload = "data={\"message\": \"Hello World\"}";
    StringEntity entity = new StringEntity(payload, ContentType.APPLICATION_FORM_URLENCODED);
    HttpResponse response = httpClient.execute(request);

    If you are calling a servlet, you can get the JSON string by calling request.getParameter("data");


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.