What is the Java 11 HttpClient, and how is it better than HttpURLConnection?

java.net.http.HttpClient, standard since Java 11, is a modern API for HTTP calls. It supports HTTP/2, synchronous and asynchronous requests, and a clean builder style, replacing the old HttpURLConnection, which was verbose and supported only HTTP/1.1.

Key Points: • Built from three parts: HttpClient (reusable, thread-safe), HttpRequest (built with a builder) and HttpResponse with a BodyHandler. • send() blocks and returns the response. sendAsync() returns a CompletableFuture. • Supports HTTP/2, timeouts, redirects, authentication, proxies and WebSocket. • Create one HttpClient and reuse it, because it manages a connection pool. • In Spring applications, RestClient (Spring 6.1+), WebClient or a Feign client are usually preferred, but the JDK client needs no extra dependency.

Code Example:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.time.Duration;

public class HttpClientDemo {

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

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.example.com/users/1"))
                .header("Accept", "application/json")
                .timeout(Duration.ofSeconds(10))
                .GET()
                .build();

        System.out.println(request.method() + " " + request.uri());
        System.out.println("Version: " + client.version());

        // Blocking call:
        // HttpResponse<String> res = client.send(request, HttpResponse.BodyHandlers.ofString());
        // Asynchronous call:
        // client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
        //       .thenApply(HttpResponse::body)
        //       .thenAccept(System.out::println);
    }
}

Output:

GET https://api.example.com/users/1 Version: HTTP_2

Good to Know: If asked which HTTP client you'd use in a Spring Boot 3 service, mention RestClient for blocking calls and WebClient for reactive ones, and add that the JDK HttpClient is a good choice for libraries or plain Java code with no Spring dependency.

Interview Tip: A concise interview answer is:

"Java 11's HttpClient is the standard replacement for HttpURLConnection. It supports HTTP/2, synchronous send and asynchronous sendAsync with CompletableFuture, timeouts and redirects, using a clean builder API, and I reuse one client because it pools connections."

Previous question: Which useful String, Stream and Optional methods were added after Java 8?

Next question: What are helpful NullPointerExceptions in Java 14+?

More Java 17 and 21 Features interview questions

All Java 17 and 21 Features questions