How do I send a POST request with JSON data using Java 11 HttpClient?

In Java 11, the HttpClient API was introduced as part of JEP 321, providing a standardized way to perform HTTP operations. To send a POST request with JSON data, you can use the HttpClient along with its HttpRequest object. Here’s a step-by-step guide and example:

Steps to Send POST Request with JSON Data in Java 11

  1. Create an instance of HttpClient:
    HttpClient is used to send HTTP requests and receive responses.

  2. Build the HttpRequest:
    Use the HttpRequest class to set the URI, HTTP method (POST), and add the JSON payload as the request body.

  3. Set the Content Type Header:
    Use the Content-Type header to specify that the content type of the request body is JSON.

  4. Send the request and handle the response:
    Use the HttpClient‘s send or sendAsync method to execute the request and retrieve the response.

Java Example: Sending a POST Request with JSON Data

package org.kodejava.net.http;

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

public class PostRequestExample {

   public static void main(String[] args) {
      // 1. Create HttpClient instance
      try (HttpClient httpClient = HttpClient.newHttpClient()) {

         // 2. JSON data to send in the POST request
         String json = """
                 {
                     "title": "nesciunt quas odio",
                     "body": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
                     "userId": 1
                 }
                 """;

         // 3. Create HttpRequest and set headers
         HttpRequest request = HttpRequest.newBuilder()
                 .uri(URI.create("https://jsonplaceholder.typicode.com/posts/")) // Replace with your API endpoint
                 .header("Content-Type", "application/json")       // Set content type to JSON
                 .POST(HttpRequest.BodyPublishers.ofString(json))  // Set the JSON as body
                 .build();

         try {
            // 4. Send the request and get HttpResponse
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            // 5. Process the response
            if (response.statusCode() == 200 || response.statusCode() == 201) {
               System.out.println("Response: " + response.body());
            } else {
               System.err.println("Failed with HTTP error code: " + response.statusCode());
            }
         } catch (IOException | InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}

Breakdown of the Example:

  1. Create HttpClient:

    HttpClient httpClient = HttpClient.newHttpClient();
    

    This creates a new instance of the HttpClient, which will be used to send/receive requests.

  2. JSON Payload:
    A JSON string is created using Java’s multi-line string feature ("""), available starting from Java 13. Alternatively, you can concatenate strings or use external libraries like Jackson to generate the JSON.

  3. Build HttpRequest:

    HttpRequest request = HttpRequest.newBuilder()
           .uri(URI.create("https://jsonplaceholder.typicode.com/posts/"))
           .header("Content-Type", "application/json")
           .POST(HttpRequest.BodyPublishers.ofString(json))
           .build();
    
    • .uri(URI): Specifies the URI (endpoint) for the request.
    • .header("Content-Type", "application/json"): Adds a header specifying the content type.
    • .POST(HttpRequest.BodyPublishers.ofString(json)): Sets the request method to POST and attaches the JSON string as the body.
  4. Send Request and Receive Response:
    HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
    
    • httpClient.send: Performs the HTTP request.
    • HttpResponse.BodyHandlers.ofString(): Specifies that the response body should be treated as a String.
  5. Handle the Response:
    The response status code and body are processed accordingly (response.statusCode() and response.body()).

Sample Output

If the request is successful, you might see output like:

Response: {
  "title": "nesciunt quas odio",
  "body": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "userId": 1,
  "id": 101
}

Notes:

  1. Replace the URL (`https://jsonplaceholder.typicode.com/posts/`) with the actual endpoint you want to call.
  2. Add error handling and retries as needed for production environments.
  3. If advanced JSON manipulation is required, consider using libraries like Jackson or Gson to build the JSON payload programmatically.

Dependencies

No external dependencies are required; this is achievable with core Java 11+ classes.

Leave a Reply

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