To read HTTP responses in Java 11 using HttpResponse.BodyHandlers, you use the Java 11 java.net.http package, which introduced the HttpClient API. The HttpResponse.BodyHandlers class provides various static methods to handle the HTTP response body in different formats, such as strings, files, or byte arrays.
Here’s a step-by-step guide to using HttpResponse.BodyHandlers with examples:
Step 1: Create an HttpClient
Start by creating an instance of the HttpClient. It’s used to send an HTTP request and receive an HTTP response.
HttpClient client = HttpClient.newHttpClient();
Step 2: Create an HttpRequest
Build an HTTP request using the HttpRequest class. Specify the URI and HTTP method (like GET, POST).
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.GET() // Optional, as GET is the default
.build();
Step 3: Use HttpResponse.BodyHandlers
The HttpResponse.BodyHandlers provides different ways to read and handle the response body.
- Reading the Response as a String You can use
BodyHandlers.ofString()to read the response body as aString.HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Response status code: " + response.statusCode()); System.out.println("Response body: " + response.body()); - Reading the Response as a Byte Array If you need the raw bytes of the response, use
BodyHandlers.ofByteArray().HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray()); System.out.println("Response status code: " + response.statusCode()); byte[] responseBody = response.body(); System.out.println("Response body length: " + responseBody.length); - Writing the Response Directly to a File To save the HTTP response directly to a file, use
BodyHandlers.ofFile(Path).Path filePath = Path.of("response.json"); HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFile(filePath)); System.out.println("Response status code: " + response.statusCode()); System.out.println("Response written to: " + filePath.toAbsolutePath()); - Using
HttpResponse.BodySubscribersfor Custom Processing For advanced use cases, you can useBodyHandlers.fromSubscriber()in combination withBodySubscribersto handle the response body in a custom way.
Step 4: Handle Exceptions
Since the send() method can throw exceptions like IOException and InterruptedException, wrap your code in a try-catch block.
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Response status code: " + response.statusCode());
System.out.println("Response body: " + response.body());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Example: Putting It All Together
package org.kodejava.net.http;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.io.IOException;
public class MainHttpHClient{
public static void main(String[] args) {
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.GET()
.build();
try {
// Using BodyHandler to read response as String
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Response Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
Common BodyHandlers Methods
| Method | Description |
|---|---|
HttpResponse.BodyHandlers.ofString() |
Read the response as a String. |
HttpResponse.BodyHandlers.ofByteArray() |
Read the response as a byte[]. |
HttpResponse.BodyHandlers.ofFile(Path path) |
Write the response directly to a file. |
HttpResponse.BodyHandlers.ofInputStream() |
Read the response body as an InputStream. |
HttpResponse.BodyHandlers.fromSubscriber(BodySubscriber<T>) |
Custom handling of response body. |
Notes:
- The
HttpClient,HttpRequest, andHttpResponseclasses are part of thejava.net.httppackage introduced in Java 11. - This API is asynchronous-capable. For better scalability, you can use the
sendAsync()method for non-blocking calls, along withCompletableFuture.
