一、什么是 RestTemplate?
RestTemplate是執行HTTP請求的同步阻塞式的客戶端,它在HTTP客戶端庫(例如JDK HttpURLConnection,Apache HttpComponents,okHttp等)基礎封裝了更加簡單易用的模板方法API,也就是說RestTemplate是一個封裝,底層的實作還是java應用開發中常用的一些HTTP客戶端,但是相對于直接使用底層的HTTP客戶端庫,它的操作更加方便、快捷,能很大程度上提升我們的開發效率,
RestTemplate作為spring-web專案的一部分,在Spring 3.0版本開始被引入,RestTemplate類通過為HTTP方法(例如GET,POST,PUT,DELETE等)提供多載的方法,提供了一種非常方便的方法訪問基于HTTP的Web服務,如果你的Web服務API基于標準的RESTful風格設計,使用效果將更加的完美,
根據Spring官方檔案及原始碼中的介紹,RestTemplate在將來的版本中它可能會被棄用,因為他們已在Spring 5中引入了WebClient作為非阻塞式Reactive HTTP客戶端,但是RestTemplate目前在Spring 社區內還是很多專案的“重度依賴”,比如說Spring Cloud,另外,RestTemplate說白了是一個客戶端API封裝,和服務端相比,非阻塞Reactive 編程的需求并沒有那么高,
二、非Spring環境下使用RestTemplate
為了方便后續開發測驗,首先介紹一個網站給大家,JSONPlaceholder是一個提供免費的在線REST API的網站,我們在開發時可以使用它提供的url地址測驗下網路請求以及請求引數,或者當我們程式需要獲取一些模擬資料、模擬圖片時也可以使用它,
RestTemplate是spring的一個rest客戶端,在spring-web這個包下,這個包雖然叫做spring-web,但是它的RestTemplate可以脫離Spring 環境使用,
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
測驗一下Hello world,使用RestTemplate發送一個GET請求,并把請求得到的JSON資料結果列印出來,
@Test
public void simpleTest()
{
RestTemplate restTemplate = new RestTemplate();
String url = "http://jsonplaceholder.typicode.com/posts/1";
String str = restTemplate.getForObject(url, String.class);
System.out.println(str);
}
服務端是JSONPlaceholder網站,幫我們提供的服務端API,需要注意的是:"http://jsonplaceholder.typicode.com/posts/1"服務URL,雖然URL里面有posts這個單詞,但是它的英文含義是:帖子或者公告,而不是我們的HTTP Post協議,所以說"http://jsonplaceholder.typicode.com/posts/1",請求的資料是:id為1的Post公告資源,列印結果如下:

這里我們只是演示了RestTemplate 最基礎的用法,RestTemplate 會寫成一個系列的文章,請大家關注,
三、Spring環境下使用RestTemplate
將maven坐標從spring-web換成spring-boot-starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
將RestTemplate配置初始化為一個Bean,這種初始化方法,是使用了JDK 自帶的HttpURLConnection作為底層HTTP客戶端實作,我們還可以把底層實作切換為Apache HttpComponents,okHttp等,我們后續章節會為大家介紹,
@Configuration
public class ContextConfig {
//默認使用JDK 自帶的HttpURLConnection作為底層實作
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate();
return restTemplate;
}
}
在需要使用RestTemplate 的位置,注入并使用即可,
@Resource //@AutoWired
private RestTemplate restTemplate;
歡迎關注我的博客,里面有很多精品合集
- 本文轉載注明出處(必須帶連接,不能只轉文字):字母哥博客,
覺得對您有幫助的話,幫我點贊、分享!您的支持是我不竭的創作動力! ,另外,筆者最近一段時間輸出了如下的精品內容,期待您的關注,
- 《手摸手教你學Spring Boot2.0》
- 《Spring Security-JWT-OAuth2一本通》
- 《實戰前后端分離RBAC權限管理系統》
- 《實戰SpringCloud微服務從青銅到王者》
- 《VUE深入淺出系列》
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/119102.html
標籤:Java

