SpringBoot下使用RestTemplate實現(xiàn)遠程服務調用的詳細過程
現(xiàn)如今的項目,由服務端向外發(fā)起網絡請求的場景,基本上處處可見。
RestTemplate是一個執(zhí)行HTTP請求的同步阻塞式工具類,它僅僅只是在 HTTP 客戶端庫(例如 JDK HttpURLConnection,Apache HttpComponents,okHttp 等)基礎上,封裝了更加簡單易用的模板方法 API,方便程序員利用已提供的模板方法發(fā)起網絡請求和處理,能很大程度上提升我們的開發(fā)效率
1、前置配置
在spring環(huán)境下使用RestTemplate
如果當前項目是SpringBoot,添加SpringBoot啟動依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>同時,將RestTemplate配置初始化為一個Bean對象
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}注意:在這種初始化方法,是使用了JDK自帶的HttpURLConnection作為底層HTTP客戶端實現(xiàn)。
在需要使用RestTemplate的位置,注入并使用即可!
@Autowired private RestTemplate restTemplate;
2、API實戰(zhàn):
RestTemplate最大的特色就是對各種網絡請求方式做了包裝,能極大的簡化開發(fā)人員的工作量,下面我們以GET、POST、PUT、DELETE為例,分別介紹各個API的使用方式
2.1 GET請求:
2.1.1 不帶參的get請求
@RestController
public class TestController {
/**
* 不帶參的get請求
* @return
*/
@RequestMapping(value = "testGet", method = RequestMethod.GET)
public User testGet(){
User user = new User();
user.setCode("200");
user.setMsg("請求成功,方法:testGet");
return user;
}
}
@Data
public class User {
private String code;
private String msg;
}@Autowired
private RestTemplate restTemplate;
/**
* 單元測試(不帶參的get請求)
*/
@Test
public void testGet(){
//請求地址
String url = "http://localhost:8080/testGet";
//發(fā)起請求,直接返回對象
User user = restTemplate.getForObject(url, User.class);
}2.1.2 帶參的get請求(使用占位符號傳參)
@RestController
public class TestController {
/**
* 帶參的get請求(restful風格)
* @return
*/
@RequestMapping(value = "testGetByRestFul/{id}/{name}", method = RequestMethod.GET)
public User testGetByRestFul(@PathVariable(value = "id") String id, @PathVariable(value = "name") String name){
User user = new User();
user.setCode("200");
user.setMsg("請求成功,方法:testGetByRestFul,請求參數(shù)id:" + id + "請求參數(shù)name:" + name);
return user;
}
}@Autowired
private RestTemplate restTemplate;
/**
* 單元測試(帶參的get請求)
*/
@Test
public void testGetByRestFul(){
//請求地址
String url = "http://localhost:8080/testGetByRestFul/{1}/{2}";
//發(fā)起請求,直接返回對象(restful風格)
User user = restTemplate.getForObject(url, User.class, "001", "張三");
}2.1.3 帶參的get請求(restful風格)
@RestController
public class TestController {
/**
* 帶參的get請求(restful風格)
* @return
*/
@RequestMapping(value = "testGetByParam", method = RequestMethod.GET)
public User testGetByParam(@RequestParam("userName") String userName,
@RequestParam("userPwd") String userPwd){
User user = new User();
user.setCode("200");
user.setMsg("請求成功,方法:testGetByParam,請求參數(shù)userName:" + userName + ",userPwd:" + userPwd);
return user;
}
}@Autowired
private RestTemplate restTemplate;
/**
* 單元測試(帶參的get請求)
*/
@Test
public void testGetByParam(){
//請求地址
String url = "http://localhost:8080/testGetByParam?userName={userName}&userPwd={userPwd}";
//請求參數(shù)
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("userName", "唐三藏");
uriVariables.put("userPwd", "123456");
//發(fā)起請求,直接返回對象(帶參數(shù)請求)
User user = restTemplate.getForObject(url, User.class, uriVariables);
}2.1.4 getForEntity使用示例
上面的所有的getForObject請求傳參方法,getForEntity都可以使用,使用方法上也幾乎是一致的,只是在返回結果接收的時候略有差別。
使用ResponseEntity<T> responseEntity來接收響應結果。用responseEntity.getBody()獲取響應體。
/**
* 單元測試
*/
@Test
public void testAllGet(){
//請求地址
String url = "http://localhost:8080/testGet";
//發(fā)起請求,返回全部信息
ResponseEntity<User> response = restTemplate.getForEntity(url, User.class);
// 獲取響應體
System.out.println("HTTP 響應body:" + response.getBody().toString());
// 以下是getForEntity比getForObject多出來的內容
HttpStatus statusCode = response.getStatusCode();
int statusCodeValue = response.getStatusCodeValue();
HttpHeaders headers = response.getHeaders();
System.out.println("HTTP 響應狀態(tài):" + statusCode);
System.out.println("HTTP 響應狀態(tài)碼:" + statusCodeValue);
System.out.println("HTTP Headers信息:" + headers);
}header設置參數(shù)
//請求頭
HttpHeaders headers = new HttpHeaders();
headers.add("token", "123456789");
//封裝請求頭
HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange('請求的url', HttpMethod.GET, formEntity, String.class);2.2 GET請求:
其實POST請求方法和GET請求方法上大同小異,RestTemplate的POST請求也包含兩個主要方法:
postForObject():返回body對象postForEntity():返回全部的信息
2.2.1 模擬表單請求
模擬表單請求,post方法測試
@RestController
public class TestController {
/**
* 模擬表單請求,post方法測試
* @return
*/
@RequestMapping(value = "testPostByForm", method = RequestMethod.POST)
public User testPostByForm(@RequestParam("userName") String userName,
@RequestParam("userPwd") String userPwd){
User user = new User();
user.setCode("200");
user.setMsg("請求成功,方法:testPostByForm,請求參數(shù)userName:" + userName + ",userPwd:" + userPwd);
return user;
}
}@Autowired
private RestTemplate restTemplate;
/**
* 模擬表單提交,post請求
*/
@Test
public void testPostByForm(){
//請求地址
String url = "http://localhost:8080/testPostByForm";
// 請求頭設置,x-www-form-urlencoded格式的數(shù)據(jù)
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//提交參數(shù)設置
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("userName", "唐三藏");
map.add("userPwd", "123456");
// 組裝請求體
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
//發(fā)起請求
User user = restTemplate.postForObject(url, request, User.class);
}2.2.2 模擬表單請求,post方法測試(接收對象)
@RestController
public class TestController {
/**
* 模擬表單請求,post方法測試
* @param request
* @return
*/
@RequestMapping(value = "testPostByFormAndObj", method = RequestMethod.POST)
public User testPostByForm(UserVO request){
User user = new User();
user.setCode("200");
user.setMsg("請求成功,方法:testPostByFormAndObj,請求參數(shù):" + JSON.toJSONString(request));
return user;
}
}
@Data
public class UserVO {
private String userName;
private String userPwd;
}@Autowired
private RestTemplate restTemplate;
/**
* 模擬表單提交,post請求
*/
@Test
public void testPostByForm(){
//請求地址
String url = "http://localhost:8080/testPostByFormAndObj";
// 請求頭設置,x-www-form-urlencoded格式的數(shù)據(jù)
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//提交參數(shù)設置
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("userName", "唐三藏");
map.add("userPwd", "123456");
// 組裝請求體
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
//發(fā)起請求
User user = restTemplate.postForObject(url, request, User.class);
}2.2.3 模擬JSON請求,post方法測試
@RestController
public class TestController {
/**
* 模擬JSON請求,post方法測試
* @param request
* @return
*/
@RequestMapping(value = "testPostByJson", method = RequestMethod.POST)
public User testPostByJson(@RequestBody UserVO request){
User user = new User();
user.setCode("200");
user.setMsg("請求成功,方法:testPostByJson,請求參數(shù):" + JSON.toJSONString(request));
return user;
}
}@Autowired
private RestTemplate restTemplate;
/**
* 模擬JSON提交,post請求
*/
@Test
public void testPostByJson(){
//請求地址
String url = "http://localhost:8080/testPostByJson";
//入?yún)?
UserVO vo = new UserVO();
vo.setUserName("唐三藏");
vo.setUserPwd("123456789");
//發(fā)送post請求,并打印結果,以String類型接收響應結果JSON字符串
ResponseBean responseBean = restTemplate.postForObject(url, vo, User.class);
}2.3 PUT請求
put請求方法,可能很多人都沒用過,它指的是修改一個已經存在的資源或者插入資源,該方法會向URL代表的資源發(fā)送一個HTTP PUT方法請求,示例如下
@RestController
public class TestController {
/**
* 模擬JSON請求,put方法測試
* @param request
* @return
*/
@RequestMapping(value = "testPutByJson", method = RequestMethod.PUT)
public void testPutByJson(@RequestBody UserVO request){
System.out.println("請求成功,方法:testPutByJson,請求參數(shù):" + JSON.toJSONString(request));
}
}@Autowired
private RestTemplate restTemplate;
/**
* 模擬JSON提交,put請求
*/
@Test
public void testPutByJson(){
//請求地址
String url = "http://localhost:8080/testPutByJson";
//入?yún)?
UserVO request = new UserVO();
request.setUserName("唐三藏");
request.setUserPwd("123456789");
//模擬JSON提交,put請求
restTemplate.put(url, request);
}2.4 DELETE請求
與之對應的還有delete方法協(xié)議,表示刪除一個已經存在的資源,該方法會向URL代表的資源發(fā)送一個HTTP DELETE方法請求。
@RestController
public class TestController {
/**
* 模擬JSON請求,delete方法測試
* @return
*/
@RequestMapping(value = "testDeleteByJson", method = RequestMethod.DELETE)
public void testDeleteByJson(){
System.out.println("請求成功,方法:testDeleteByJson");
}
}@Autowired
private RestTemplate restTemplate;
/**
* 模擬JSON提交,delete請求
*/
@Test
public void testDeleteByJson(){
//請求地址
String url = "http://localhost:8080/testDeleteByJson";
//模擬JSON提交,delete請求
restTemplate.delete(url);
}2.5 Exchange方法
如果以上方法還不滿足你的要求。在RestTemplate工具類里面,還有一個exchange通用協(xié)議請求方法,它可以發(fā)送GET、POST、DELETE、PUT、OPTIONS、PATCH等等HTTP方法請求。
到此這篇關于SpringBoot下使用RestTemplate實現(xiàn)遠程服務調用的詳細過程的文章就介紹到這了,更多相關SpringBoot RestTemplate遠程服務調用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java延時任務實現(xiàn)方案及四大典型場景詳解(適用于Spring?Boot3)
在Java編程中,延時函數(shù)是一種常用的技術,用于在程序執(zhí)行過程中暫停一段時間,這篇文章主要介紹了Java延時任務實現(xiàn)方案及四大典型場景(適用于SpringBoot3)的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2026-05-05
Java實戰(zhàn)員工績效管理系統(tǒng)的實現(xiàn)流程
只學書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+Mysql+Maven+HTML實現(xiàn)一個員工績效管理系統(tǒng),大家可以在過程中查缺補漏,提升水平2022-01-01
SpringBoot?UserAgentUtils獲取用戶瀏覽器的用法
UserAgentUtils是于處理用戶代理(User-Agent)字符串的工具類,一般用于解析和處理瀏覽器、操作系統(tǒng)以及設備等相關信息,這些信息通常包含在接口請求的?User-Agent?字符串中,本文介紹SpringBoot?UserAgentUtils獲取用戶瀏覽器的用法,感興趣的朋友一起看看吧2025-04-04
java servlet手機app訪問接口(三)高德地圖云存儲及檢索
這篇文章主要為大家詳細介紹了java servlet手機app訪問接口(三),高德地圖云存儲及檢索,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12
Mybatis的mapper.xml中if標簽test判斷的用法說明
這篇文章主要介紹了Mybatis的mapper.xml中if標簽test判斷的用法說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06

