Spring 6.1 新特性:RestClient

工程 | Arjen Poutsma | 2023年7月13日 | ...

Spring Framework 6.1 M2 引入了 RestClient,這是一個新的同步 HTTP 客戶端。顧名思義,RestClient 提供了 WebClient 的流暢 API,並沿用了 RestTemplate 的基礎設施。

十四年前,當 Spring Framework 3.0 引入 RestTemplate 時,我們很快發現將 HTTP 的所有功能都暴露在一個模板類中會導致過多的過載方法。因此,在 Spring Framework 5 中,我們為響應式 WebClient 使用了流暢的 API。透過 RestClient,我們引入了一個 HTTP 客戶端,它提供類似於 WebClient 的 API,並使用 RestTemplate 的訊息轉換器、請求工廠、攔截器和其他底層元件。

建立 RestClient

您可以使用靜態 create 方法之一建立 RestClient。您還可以使用 RestClient::builder 來獲取一個具有更多選項的構建器,例如指定要使用的 HTTP 客戶端、設定預設 URL、路徑變數和請求頭,或註冊攔截器和初始化器。

使用 RestClient::create(RestTemplate),您可以使用現有 RestTemplate 的配置初始化 RestClient

檢索

讓我們建立一個 RestClient,用它來設定一個基本的 GET 請求,並使用 retrieve 將站點內容作為字串檢索。

RestClient restClient = RestClient.create();

String result = restClient.get()
  .uri("https://example.com")
  .retrieve()
  .body(String.class);
System.out.println(result);

如果您對響應狀態碼和請求頭感興趣,而不僅僅是內容,您可以使用 toEntity 來獲取 ResponseEntity

ResponseEntity<String> result = restClient.get()
  .uri("https://example.com")
  .retrieve()
  .toEntity(String.class);

System.out.println("Response status: " + result.getStatusCode());
System.out.println("Response headers: " + result.getHeaders());
System.out.println("Contents: " + result.getBody());

RestClient 還可以使用 Jackson 在底層將 JSON 轉換為物件。事實上,它可以使用 RestTemplate 支援的所有型別進行轉換,因為它使用相同的訊息轉換器。注意 URI 變數的用法,以及 Accept 請求頭設定為 JSON。

int id = ...
Pet pet = restClient.get()
  .uri("https://petclinic.example.com/pets/{id}", id)
  .accept(APPLICATION_JSON)
  .retrieve()
  .body(Pet.class);

POST

執行 POST 請求同樣簡單,如下所示:

Pet pet = ...
ResponseEntity<Void> response = restClient.post()
  .uri("https://petclinic.example.com/pets/new")
  .contentType(APPLICATION_JSON)
  .body(pet)
  .retrieve()
  .toBodilessEntity();

錯誤處理

預設情況下,當接收到 4xx 或 5xx 狀態碼時,RestClient 會丟擲 RestClientException 的子類。此行為可以使用狀態處理器覆蓋,如下所示:

String result = restClient.get()
  .uri("https://example.com/this-url-does-not-exist")
  .retrieve()
  .onStatus(HttpStatusCode::is4xxClientError, (request, response) -> {
      throw new MyCustomRuntimeException(response.getStatusCode(), response.getHeaders())
  })
  .body(String.class);

交換

RestClient 為更高階的場景提供了 exchange 方法,因為它提供了對底層 HTTP 請求和響應的訪問。當您使用 exchange 時,前面提到的狀態處理器不會應用,因為 exchange 函式已經提供了對完整響應的訪問,允許您執行任何必要的錯誤處理。

Pet result = restClient.get()
  .uri("https://petclinic.example.com/pets/{id}", id)
  .accept(APPLICATION_JSON)
  .exchange((request, response) -> {
    if (response.getStatusCode().is4xxClientError()) {
      throw new MyCustomRuntimeException(response.getStatusCode(), response.getHeaders());
    }
    else {
      Pet pet = convertResponse(response);
      return pet;
    }
  });

RestClient 的支援

RestClient 只是 Spring Framework 6.1 提供的眾多功能之一。各種元件已經支援 RestClient:您可以透過 MockRestServiceServer 測試其用法,或者將其用作 @HttpExchange 介面的後端。

此外,Spring Boot 3.2 M1 將包括對 RestClient 的支援。

獲取 Spring 新聞通訊

透過 Spring 新聞通訊保持聯絡

訂閱

領先一步

VMware 提供培訓和認證,助您加速進步。

瞭解更多

獲得支援

Tanzu Spring 提供 OpenJDK™、Spring 和 Apache Tomcat® 的支援和二進位制檔案,只需一份簡單的訂閱。

瞭解更多

即將舉行的活動

檢視 Spring 社群所有即將舉行的活動。

檢視所有