Java HttpClient POST Request Example

In this tutorial, we will see how to use Java 11 HttpClient API to submit form data and also we will see how to use Java 11 HttpClient API to send JSON data to the server.

Java 11 introduced a new standard HTTP client library called HttpClient that provides a more modern and flexible way to send HTTP requests and handle responses. The new HttpClient is designed to be more efficient, scalable, and capable than the legacy HttpURLConnection API, and supports both synchronous and asynchronous request processing.

Java HttpClient POST Request Example - Send Form Data 

This is a Java program that sends an HTTP POST request to the URL https://httpbin.org/post, along with some data in the request body. The response from the server is then printed to the console.
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Main {

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

        Map<Object, Object> data = new HashMap<>();
        data.put("fistname", "admin");
        data.put("lastname", "admin");
        data.put("age", 25);

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .header("Content-Type", "application/x-www-form-urlencoded")
                .uri(URI.create("https://httpbin.org/post"))
                .POST(ofForm(data))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status code: " + response.statusCode());
        System.out.println("\n Body: " + response.body());
    }

    public static HttpRequest.BodyPublisher ofForm(Map<Object, Object> data) {

        StringBuilder body = new StringBuilder();

        for (Object dataKey : data.keySet()) {

            if (body.length() > 0) {
                body.append("&");
            }

            body.append(encode(dataKey))
                    .append("=")
                    .append(encode(data.get(dataKey)));
        }

        return HttpRequest.BodyPublishers.ofString(body.toString());
    }

    private static String encode(Object obj) {
        return URLEncoder.encode(obj.toString(), StandardCharsets.UTF_8);
    }
}

Output:

Status code: 200

 Body: {
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "age": "25", 
    "fistname": "admin", 
    "lastname": "admin"
  }, 
  "headers": {
    "Content-Length": "36", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Java-http-client/17.0.2", 
    "X-Amzn-Trace-Id": "Root=1-63070225-277b1f41012b39780e96a216"
  }, 
  "json": null, 
  "origin": "103.59.74.90", 
  "url": "https://httpbin.org/post"
}

Java HttpClient POST Request JSON Example - Send JSON Data

This Java program uses HTTP Client API to submit form data in a JSON format(application/json).

import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {

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

        // json formatted data
        String json = new StringBuilder()
                .append("{")
                .append("\"firstName\":\"tom\",")
                .append("\"lastName\":\"cruise\",")
                .append("\"age\":\"50\"")
                .append("}").toString();

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .header("Content-Type", "application/json")
                .uri(URI.create("https://httpbin.org/post"))
                .POST(HttpRequest.BodyPublishers.ofString(json))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status code: " + response.statusCode());
        System.out.println("\n Body: " + response.body());
    }
}
This Java code sends an HTTP POST request to a RESTful web service and sends a JSON payload in the request body. It then prints the response status code and body to the console.

Output:

Status code: 200

 Body: {
  "args": {}, 
  "data": "{\"firstName\":\"tom\",\"lastName\":\"cruise\",\"age\":\"50\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Content-Length": "50", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "User-Agent": "Java-http-client/17.0.2", 
    "X-Amzn-Trace-Id": "Root=1-63070480-32c7ceee01c7433d7dc18550"
  }, 
  "json": {
    "age": "50", 
    "firstName": "tom", 
    "lastName": "cruise"
  }, 
  "origin": "103.59.74.90", 
  "url": "https://httpbin.org/post"
}

Conclusion

In this tutorial, we have seen how to use Java 11 HTTP Client API to submit form data and also we will see how to use Java 11 HTTP Client API to send JSON data to the server.

Comments