Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Các lớp Http/2 Client trong Java 9

HTTP/2 là phiên bản mới của giao thức HTTP, cải tiến cách khung (frame) và truyền dữ liệu giữa client-server. Java 9 giới thiệu API mới (incubator module jdk.incubator.httpclient) với 3 lớp chính, thay thế HttpURLConnection cũ.

3 lớp cốt lõi

LớpChức năng
HttpClientTạo và gửi request, quản lý kết nối, redirect, authentication, proxy.
HttpRequestXây dựng request: URI, method (GET/POST...), headers, body, timeout.
HttpResponse<T>Chứa response: status code, headers, body (String, byte[], InputStream...).

Ví dụ gửi GET request

// Tạo HttpClient
HttpClient httpClient = HttpClient.newHttpClient();
System.out.println(httpClient.version()); // HTTP_2

// Xây dựng HttpRequest
HttpRequest httpRequest = HttpRequest.newBuilder()
    .uri(new URI("https://www.tutorialspoint.com/"))
    .GET()
    .build();

// In headers request
Map<String, List<String>> headers = httpRequest.headers().map();
headers.forEach((k, v) -> System.out.println(k + "-" + v));

// Gửi request, nhận response body dạng String
HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandler.asString());

// Output body
System.out.println("Response: " + httpResponse.body());

Điểm mạnh HTTP/2 Client

  • Hỗ trợ HTTP/2 (multiplexing, header compression, server push).
  • API fluent, hiện đại, hỗ trợ async (sendAsync() trả về CompletableFuture).
  • Không cần thư viện thứ 3 (Apache HttpClient, OkHttp...).
  • Tích hợp sẵn trong JDK (từ Java 11 thành module chuẩn java.net.http).

Lưu ý: Java 9 là incubator module, cần --add-modules jdk.incubator.httpclient. Từ Java 11 trở đi thành module chuẩn.