Java 11 introduced a new HttpClient API (java.net.HttpClient) that simplifies making HTTP requests and handling responses. It provides a clean and concise way to perform synchronous and asynchronous HTTP operations, and it fully supports RESTful APIs.
Here’s a step-by-step guide with examples for how to use the Java 11 HttpClient to call REST APIs.
1. Create an HttpClient Instance
The HttpClient
is the main entry point for sending HTTP requests and receiving responses. You can create an HttpClient
using its builder.
HttpClient client = HttpClient.newHttpClient();
2. Build an HttpRequest
The HttpRequest
represents the HTTP request that you want to send. You can build it using a static builder where you set the HTTP method, headers, URI, etc.
Example: Build a GET Request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.GET() // Use GET method
.build();
Example: Build a POST Request
For a POST request, you also need to include a body in the request.
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}"))
.build();
3. Send the HttpRequest
The HttpClient
provides methods to send HTTP requests. You can choose to execute the request synchronously or asynchronously.
Synchronous Call
Use HttpClient.send()
to execute the request synchronously and retrieve an HttpResponse
.
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
Asynchronous Call
Use HttpClient.sendAsync()
to execute the request asynchronously. It returns a CompletableFuture
which allows non-blocking operations.
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body) // Extract body
.thenAccept(System.out::println); // Print response body
The above code sends the request in the background and processes the response once received.
4. Handle Response
The HttpResponse
provides access to the response details like status code, headers, and body. You can use HttpResponse.BodyHandlers
to specify how the body should be processed.
Available BodyHandlers:
HttpResponse.BodyHandlers.ofString()
: Read the response as aString
.HttpResponse.BodyHandlers.ofFile()
: Save the response to a file.HttpResponse.BodyHandlers.ofInputStream()
: Access the response as anInputStream
.
For example:
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Headers: " + response.headers());
System.out.println("Body: " + response.body());
5. Complete Example for a GET Request
Here’s a complete program that sends a GET request to a REST API and prints the response:
package org.kodejava.net.http;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpClientGetExample {
public static void main(String[] args) {
try {
// Step 1: Create HttpClient
HttpClient client = HttpClient.newHttpClient();
// Step 2: Create HttpRequest
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.GET()
.build();
// Step 3: Send the request and receive HttpResponse
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Step 4: Process the response
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}
6. Complete Example for a POST Request
Here’s how you can do a POST request to send JSON data:
package org.kodejava.net.http;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpClientPostExample {
public static void main(String[] args) {
try {
// Step 1: Create HttpClient
HttpClient client = HttpClient.newHttpClient();
// Step 2: Build HttpRequest with POST body
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}"))
.build();
// Step 3: Send the POST request and receive response
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Step 4: Process the response
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Key Points to Remember:
- Use
java.net.URI
for specifying the API endpoint. - Always handle exceptions (e.g.,
IOException
andInterruptedException
). - You may need to set headers (e.g.,
Content-Type
orAuthorization
) depending on the API requirements. - Handle different response codes appropriately.
This approach is suitable for working with REST APIs and provides both blocking and non-blocking operations for flexibility.