Advertisement
Beginner Java, Java Networking & HTTP Client

What is the modern java.net.http.HttpClient (introduced in Java 11), and how does it improve on the older HttpURLConnection for making HTTP requests?

Short answer

HttpClient provides a modern, fluent, builder-based API for constructing and sending HTTP requests (supporting HTTP/1.1 and HTTP/2, synchronous and asynchronous execution, and built-in support for common needs like redirects and timeouts) -- it significantly improves on the…

Save Java mock interview
Advertisement
AModel answer
HttpClient provides a modern, fluent, builder-based API for constructing and sending HTTP requests (supporting HTTP/1.1 and HTTP/2, synchronous and asynchronous execution, and built-in support for common needs like redirects and timeouts) -- it significantly improves on the older HttpURLConnection, which was notoriously awkward and error-prone to use correctly (a confusing, low-level API originally designed decades ago, requiring careful manual handling of connection setup, streams, and error codes), making HttpClient the clearly recommended choice for any new Java code needing to make HTTP requests without pulling in a third-party library like Apache HttpClient or OkHttp.
HttpClient client = HttpClient.newHttpClient();

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

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
Real-world example
A microservice calling an external REST API migrates from the older, awkward HttpURLConnection (requiring manual stream management and confusing connection state handling) to the modern HttpClient, immediately simplifying the code with its fluent builder API and built-in JSON-friendly string body handling.
Likely follow-ups
  • Why did the JDK team decide to introduce an entirely new HTTP client rather than improving HttpURLConnection directly?
  • What third-party libraries (like Apache HttpClient or OkHttp) were commonly used to work around HttpURLConnection's limitations before Java 11?
Related topics