第十二篇:Spring Boot之使用Spring RestTemplate訪問Rest服務
阿新 • • 發佈:2018-12-29
RestTemplate是Spring3.0後開始提供的用於訪問 Rest 服務的輕量級客戶端,相較於傳統的HttpURLConnection、Apache HttpClient、OkHttp等框架,RestTemplate大大簡化了發起HTTP請求以及處理響應的過程。這篇文章主要介紹怎麼用RestTemplate消費一個 Restful的web服務。
RestTemplate支援多種的請求方式,具體參考下表:
HTTP method | RestTemplate methods |
---|---|
GET | getForObject、getForEntity |
POST | postForObject、postForEntity、postForLocation |
PUT | put |
DELETE | delete |
HEAD | headForHeaders |
OPTIONS | optionsForAllow |
PATCH | patchForObject |
any | exchange、execute |
更多詳情,請檢視api
構架工程
建立一個springboot工程,去消費RESTFUL的服務。這個服務是 http://gturnquist-quoters.cfapps.io/api/random ,它會隨機返回Json字串。在Spring專案中,它提供了一個非常簡便的類,叫RestTemplate,它可以很簡便的消費服務。
消費服務
通過RestTemplate消費服務,需要先context中註冊一個RestTemplate bean。程式碼如下:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
String quote = restTemplate.getForObject(
"http://gturnquist-quoters.cfapps.io/api/random", String.class);
log.info(quote.toString());
};
}