Q62: What is the modern HttpClient API introduced in Java 11?

Java 11 replaced legacy HttpURLConnection with java.net.http.HttpClient.

  • Features: Supports HTTP/1.1 and HTTP/2, WebSockets, non-blocking asynchronous requests via CompletableFuture, reactive stream body handlers (BodyHandlers.ofString()).
Java 11 HttpClient Async Request
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/data"))
    .GET()
    .build();

client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
    .thenApply(HttpResponse::body)
    .thenAccept(System.out::println);
💡 HttpClient supports non-blocking asynchronous HTTP requests using CompletableFuture.
Key Takeaways
  • Native support for HTTP/2, WebSockets, and non-blocking async requests.
Knowledge Check

Which protocol is supported natively by the Java 11 HttpClient API out of the box?