先行一步
VMware 提供培訓和認證,助您加速進步。
瞭解更多Spring Framework 6.1 M2 引入了 RestClient
,一個新的同步 HTTP 客戶端。顧名思義,RestClient
提供了 WebClient
的流暢 API 以及 RestTemplate
的基礎設施。
十四年前,當 RestTemplate
在 Spring Framework 3.0 中被引入時,我們很快發現,在一個模板類中暴露 HTTP 的所有能力會導致過多的過載方法。因此,在 Spring Framework 5 中,我們為響應式 WebClient
使用了流暢 API。藉助 RestClient
,我們引入了一個提供類似於 WebClient
API 的 HTTP 客戶端,並且它使用 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
也可以將 JSON 轉換為物件,底層使用了 Jackson。實際上,它可以使用與 RestTemplate
相同的訊息轉換器,因此可以轉換 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
請求也同樣簡單,如下所示
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
的支援。