Java 9 中有哪些不同的 Http/2 客戶端類?


Http/2 Http 協議的更新版本。Http/2的改進包括專注於資料如何以框架形式表示並在伺服器與客戶端之間傳輸。在這個 Http/2 協議新版本中,Http 客戶端、請求響應分別定義在各自獨立的類中。新的 API 使得Http 連線更易於維護,速度更快,並且無需藉助第三方庫即可支援響應速度更快的應用程式。

新的 API 透過三個類來處理 HTTP 連線。

  • HttpClient:該類用於處理建立和傳送請求。
  • HttpRequest:該類用於構造透過 HttpClient 傳送的請求。
  • HttpResponse:該類儲存已傳送請求的響應。

在下面的程式碼片段中,我們需要向特定 URL 傳送請求並接收響應。

// Create an HttpClient object   
   HttpClient httpClient = HttpClient.newHttpClient();
   System.out.println(httpClient.version());

// Build a HTTPRequest
   HttpRequest httpRequest = HttpRequest.newBuilder().uri(new  URI("https://tutorialspoint.tw/")).GET().build(); // create a GET request for the given URI
   Map<String, List<String>> headers = httpRequest.headers().map();
   headers.forEach((k, v) -> System.out.println(k + "-" + v));

// Send the request
   HttpResponse httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandler.asString());

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

更新於: 2020 年 3 月 25 日

128 次瀏覽

開啟你的職業

完成課程,獲得認證

馬上開始
廣告