In order to send requests asynchronously, the HTTP Client API relies on CompletableFeature, as discussed in Chapter 11, Concurrency – Deep Dive, and the sendAsync() method, as follows:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://reqres.in/api/users/2"))
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.exceptionally(e -> "Exception: " + e)
.thenAccept(System.out::println)
.get(30, TimeUnit.SECONDS); // or join()
Alternatively, let's assume that, while waiting for the response, we want to execute other tasks as well:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://reqres.in/api/users/2"))
.build();
CompletableFuture<String> response
= client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.exceptionally(e -> "Exception: " + e);
while (!response.isDone()) {
Thread.sleep(50);
System.out.println("Perform other tasks
while waiting for the response ...");
}
String body = response.get(30, TimeUnit.SECONDS); // or join()
System.out.println("Body: " + body);