Http/2 Client API (Java 9 incubator module jdk.incubator.httpclient) cải tiến hiệu năng so với HTTP/1.1, hỗ trợ server push. Làm web nhanh hơn, hiệu quả hơn. Export package jdk.incubator.http chứa public API.
Kích hoạt trong JShell
C:\> jshell -v --add-modules jdk.incubator.httpclient | Welcome to JShell -- Version 9.0.4
Ví dụ đầy đủ trong JShell
jshell> import jdk.incubator.http.*;
jshell> HttpClient httpClient = HttpClient.newHttpClient();
httpClient ==> jdk.incubator.http.HttpClientImpl@534df152
jshell> HttpRequest httpRequest = HttpRequest.newBuilder()
...> .uri(new URI("https://www.google.com"))
...> .GET()
...> .build();
httpRequest ==> https://www.google.com GET
jshell> HttpResponse httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandler.asString());
httpResponse ==> jdk.incubator.http.HttpResponseImpl@609cd4d8
jshell> System.out.println(httpResponse.statusCode());
403
jshell> System.out.println(httpResponse.body());
<HTML response body>
3 lớp cốt lõi
| Lớp | Mô tả |
|---|---|
| HttpClient | Tạo, cấu hình, gửi request (sync/async), quản lý connection pool, cookie, proxy, authenticator. |
| HttpRequest | Immutable builder: URI, method, headers, body (String, byte[], InputStream, Publisher), timeout, version (HTTP/1.1, HTTP/2). |
| HttpResponse<T> | Immutable: statusCode, headers, body (type T), version, URI. Body handler: asString(), asByteArray(), asInputStream(), discarding(), ofLines()... |
Điểm mạnh
- Hỗ trợ HTTP/2 (multiplexing, header compression HPACK, server push).
- Async native:
sendAsync()trảCompletableFuture<HttpResponse>. - Reactive Streams: body handler
BodyHandler.asSubscriber()cho backpressure. - WebSocket support (Java 11+).
- Không cần dependency external (Apache HttpClient, OkHttp).
Lưu ý
Java 9: incubator module (--add-modules jdk.incubator.httpclient). Java 11+: module chuẩn java.net.http, package java.net.http.