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?
IntermediateAnswer
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 arrivesReal-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.