All 15 Java Networking & HTTP Client questions
More in Java Networking & HTTP Client
Advertisement
Back to results for “Background Tasks”
Java › Java Networking & HTTP Client

How would you make an asynchronous, non-blocking HTTP request using HttpClient's sendAsync() method, and how does the returned CompletableFuture integrate with the rest of an asynchronous pipeline?

Intermediate

Answer

client.sendAsync(request, bodyHandler) immediately returns a CompletableFuture<HttpResponse<T>> without blocking the calling thread, letting you compose the eventual response using CompletableFuture's fluent chaining methods (thenApply(), thenAccept(), exceptionally()) to process the result once it arrives, integrating naturally with other asynchronous work in a larger reactive or CompletableFuture-based application pipeline rather than dedicating a thread to block waiting for each individual HTTP call to complete.
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/data"))
    .build();

CompletableFuture<String> futureBody = client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
    .thenApply(HttpResponse::body)
    .exceptionally(ex -> {
        System.err.println("Request failed: " + ex.getMessage());
        return "";
    });

futureBody.thenAccept(System.out::println);  // processes the result once it eventually arrives
Real-world example A dashboard service fetching data concurrently from five independent external APIs uses sendAsync() for all five requests simultaneously, combining their resulting CompletableFutures with CompletableFuture.allOf() to wait for all responses together, achieving far better overall latency than issuing five sequential blocking requests one after another.

Common follow-ups: How would you set a per-request timeout that's independent of the HttpClient's own default connection timeout?;What thread does the CompletableFuture's continuation callbacks (like thenApply) actually execute on by default?