
Http/2 是Http 協定的較新版本。 Http/2 的改進包括專注於資料在伺服器和用戶端之間的建置和傳輸方式。在這個新版本的Http/2協定中,為Http#客戶端、請求和回應定義了單獨的類別強>。新的 API 使 Http 連接更容易維護、更快速,並且無需第三方程式庫即可實現響應速度更快的應用程式。
新的 API 透過三個類別處理 HTTP 連線。
-
HttpClient:它處理請求的建立和傳送。
- HttpRequest:它用來建構要透過HttpClient傳送的請求。
-
HttpResponse:它保存已傳送請求的回應。
在下面的程式碼片段中,我們需要向特定的 URL 發送請求並接收回應。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <strong>
<strong> HttpClient </strong>httpClient = <strong>HttpClient.newHttpClient()</strong>;
System.out.println(<strong>httpClient.version()</strong>);
<strong>
</strong><strong> HttpRequest </strong>httpRequest = HttpRequest.newBuilder().uri( new URI( "https://www.tutorialspoint.com/" )).<strong>GET</strong>().build(); <strong>// create a GET request for the given URI</strong>
<strong>Map</strong><strong><String, List<String></strong>> headers = httpRequest.headers().map();
headers.forEach((k, v) -> System.out.println(k + "-" + v));
<strong>
</strong><strong> HttpResponse </strong>httpResponse = httpClient.<strong>send</strong>(httpRequest, HttpResponse.BodyHandler.asString());
<strong>
</strong> System.out.println( "Response: " + httpResponse.<strong>body()</strong>);
|
登入後複製
以上是在Java 9中有哪些不同的Http/2客戶端類別?的詳細內容。更多資訊請關注PHP中文網其他相關文章!