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
- Create an instance of
HttpClient
:
HttpClient
is used to send HTTP requests and receive responses. -
Build the
HttpRequest
:
Use theHttpRequest
class to set the URI, HTTP method (POST), and add the JSON payload as the request body. -
Set the Content Type Header:
Use theContent-Type
header to specify that the content type of the request body is JSON. -
Send the request and handle the response:
Use theHttpClient
‘ssend
orsendAsync
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:
-
Create
HttpClient
:HttpClient httpClient = HttpClient.newHttpClient();
This creates a new instance of the
HttpClient
, which will be used to send/receive requests. -
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. -
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.
- 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 aString
.
- Handle the Response:
The response status code and body are processed accordingly (response.statusCode()
andresponse.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:
- Replace the URL (`https://jsonplaceholder.typicode.com/posts/`) with the actual endpoint you want to call.
- Add error handling and retries as needed for production environments.
- 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.