Sub topic 3
Asynchronous Calls with the Java HttpClient
Assume Java 11 or later, basic HTTP, checked exceptions, and CompletableFuture. sendAsync returns immediately with a CompletableFuture, an object that represents a result available later.
Start asynchronous work
The future can transform a response, handle errors, and combine several requests without blocking the calling thread.
import java.net.URI;
import java.net.http.*;
import java.util.concurrent.CompletableFuture;
public class AsyncGet {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://example.com/")).GET().build();
CompletableFuture<String> result = client
.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
if (response.statusCode() / 100 != 2) {
throw new IllegalStateException(
"HTTP status " + response.statusCode());
}
return response.body();
});
result.thenAccept(System.out::println)
.exceptionally(error -> {
System.err.println("Request failed: " + error);
return null;
})
.join();
}
}join is used here only to keep the short-lived program alive. A server or GUI application usually continues doing other work instead.
JSON and redirects
HttpClient does not parse JSON. Send JSON as a string and use a library such as Jackson to read the response.
HttpRequest request = HttpRequest.newBuilder(uri)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"widget\"}"))
.build();JsonNode value = new ObjectMapper().readTree(response.body());
String name = value.get("name").asText();Choose a redirect policy when building the client:
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.build();NORMAL follows typical redirects but does not automatically follow every insecure downgrade.
Authentication and concurrent calls
Use an Authorization header for a token. Do not log the token. An Authenticator can provide credentials for supported challenge-based authentication.
HttpRequest request = HttpRequest.newBuilder(uri)
.header("Authorization", "Bearer " + token)
.build();Reuse one client. It can safely serve concurrent requests and reuse connections.
Large transfers and protocol choices
Use BodyHandlers.ofFile(path) to write a large response directly to disk. Use BodyHandlers.ofLines() to process text incrementally. For uploads, BodyPublishers.ofFile(path) avoids constructing one large string.
Set HTTP_2 when the server supports it; otherwise the client can negotiate or use HTTP/1.1.
Retries and advanced configuration
HttpClient does not provide an application retry policy. Build retries around send or sendAsync, retrying only safe failures with bounded exponential backoff. Avoid blindly retrying non-idempotent requests.
Proxy selection, cookies, TLS settings, and custom executors are configured on HttpClient.Builder. These settings affect the client, so create separate clients when their policies differ.
Exercise
Why should several asynchronous requests share one HttpClient?
Show answer
The client is safe for concurrent use and can reuse connections, reducing setup cost and simplifying configuration.