HTTP Client Async Request Chaining

Send asynchronous HTTP requests with java.net.http.HttpClient, apply per-request timeouts, and chain response handling with CompletableFuture.

JavaData Fetching

Code

snippet
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;

public class AsyncHttpClient {

    public static void main(String[] args) {
        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(5))
                .followRedirects(HttpClient.Redirect.NORMAL)
                .build();

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.github.com/repos/openjdk/jdk"))
                .timeout(Duration.ofSeconds(10))
                .header("Accept", "application/vnd.github+json")
                .GET()
                .build();

        CompletableFuture<HttpResponse<String>> future =
                client.sendAsync(request, HttpResponse.BodyHandlers.ofString());

        future
                .thenApply(HttpResponse::body)
                .thenApply(body -> body.length() > 120 ? body.substring(0, 120) + "..." : body)
                .thenAccept(System.out::println)
                .exceptionally(ex -> {
                    System.err.println("request failed: " + ex.getMessage());
                    return null;
                })
                .join();
    }
}

How the snippet works

HTTP Client Async Request Chaining keeps everything in the class AsyncHttpClient and the function main.

The whole flow sits in the class AsyncHttpClient and the function main. The client is built once with connectTimeout(Duration.ofSeconds(5)) and Redirect.NORMAL; the request targets https://api.github.com/repos/openjdk/jdk with a per-request timeout(Duration.ofSeconds(10)) and a GitHub Accept header. client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) returns a CompletableFuture<HttpResponse<String>>, and the chain cuts the body to 120 characters with substring(0, 120) + "...", prints it via thenAccept(System.out::println), routes any failure to stderr through .exceptionally(...), and join() blocks until the chain settles.

Interactive Tools for This Topic

FAQ

How do you run HTTP Client Async Request Chaining?
Just run the file; everything it needs ships with the runtime itself.