Spring給我們提供了一個RestTemplate的API,可以方便的實現Http請求的發送。
同步客戶端執行HTTP請求,在底層HTTP客戶端庫(如JDK HttpURLConnection、Apache HttpComponents等)上公開一個簡單的模板方法API。RestTemplate通過HTTP方法為常見場景提供了模板,此外還提供了支持不太常見情況的通用交換和執行方法。 RestTemplate通常用作共享組件。然而,它的配置不支持并發修改,因此它的配置通常是在啟動時準備的。如果需要,您可以在啟動時創建多個不同配置的RestTemplate實例。如果這些實例需要共享HTTP客戶端資源,它們可以使用相同的底層ClientHttpRequestFactory。 注意:從5.0開始,這個類處于維護模式,只有對更改和錯誤的小請求才會被接受。請考慮使用org.springframework.web.react .client. webclient,它有更現代的API,支持同步、異步和流場景。
1. 添加依賴
首先,確保你的Spring Boot項目中已經添加了spring-web
依賴,因為RestTemplate
類包含在這個模塊中。
<!-- 在pom.xml中添加依賴 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.創建配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate() {return new RestTemplate();}
}
3. 使用RestTemplate
在你的服務類中,你可以通過注入RestTemplate
Bean來使用它。
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.stereotype.Service;@Service
public class MyService {private final RestTemplate restTemplate;// 通過構造器注入 RestTemplatepublic MyService(RestTemplate restTemplate) {this.restTemplate = restTemplate;}public String fetchDataFromApi(String url) {// 使用 RestTemplate 發送 GET 請求ResponseEntity<String> response = restTemplate.exchange(url,//請求路徑org.springframework.http.HttpMethod.GET,//請求方式null,//請求實體String.class // 指定響應體類型為 String);if(!response.getStatusCode().is2xxSuccessful()){// 查詢失敗,直接結束return;}// 返回響應體return response.getBody();}
}