Java 11 introduced the standardized HTTP Client API (module java.net.http, package java.net.http) as part of JEP 321, replacing the legacy HttpURLConnection with a modern, flexible, and feature-rich API. It supports HTTP/1.1, HTTP/2, WebSocket, and both synchronous and asynchronous requests, eliminating the need for third-party libraries like Apache HttpClient for many use cases. Below is a comprehensive overview of the API, its key features, and examples, tailored to complement your previous query about new String class methods in Java 11.
Key Features of the HTTP Client API
- HTTP/1.1 and HTTP/2 Support:
- Defaults to HTTP/2 for better performance (e.g., multiplexing, header compression, server push).
- Automatically downgrades to HTTP/1.1 if the server doesn’t support HTTP/2.
- Synchronous and Asynchronous Requests:
- Synchronous: Blocks until the response is received (send() method).
- Asynchronous: Non-blocking, returns a CompletableFuture (sendAsync() method).
- WebSocket Support:
- Enables real-time, bidirectional communication with low overhead.
- Reactive Streams:
- Handles request/response bodies as reactive streams via BodyPublisher and BodySubscriber.
- Builder Pattern:
- Uses fluent builders for HttpClient, HttpRequest, and WebSocket configuration.
- Immutability:
- HttpClient and HttpRequest are immutable, thread-safe, and reusable for multiple requests.
- Configuration Options:
- Supports timeouts, redirects, proxies, authentication, and SSL settings.
- Body Handlers/Publishers:
- Predefined handlers for common types (e.g., String, byte[], File) and custom reactive stream implementations.
Core Components
- HttpClient: Main entry point for sending requests and receiving responses. Created via HttpClient.newHttpClient() or HttpClient.newBuilder().
- HttpRequest: Represents an HTTP request (e.g., GET, POST) with URI, headers, and body. Built using HttpRequest.newBuilder().
- HttpResponse: Encapsulates the response, including status code, headers, and body. Uses BodyHandler to process the response body.
- BodyHandlers/BodyPublishers: Utilities to handle request/response bodies (e.g., ofString, ofFile, ofByteArray).
- WebSocket: Supports real-time communication, created via HttpClient.newWebSocketBuilder().
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/get"))
.GET()
.header("User-Agent", "Java 11 HttpClient")
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println("Body: " + response.body());
}
}
//Output
Status: 200
Body: {
"args": {},
"headers": {
"Host": "httpbin.org",
"User-Agent": "Java 11 HttpClient",
"X-Amzn-Trace-Id": "Root=1-680cf500-64931d2644016cef1c9cd7ae"
},
"origin": "157.47.39.60",
"url": "https://httpbin.org/get"
}
Code language: JavaScript (javascript)