SpringBoot下使用RestTemplate實(shí)現(xiàn)遠(yuǎn)程服務(wù)調(diào)用的詳細(xì)過程
現(xiàn)如今的項(xiàng)目,由服務(wù)端向外發(fā)起網(wǎng)絡(luò)請(qǐng)求的場(chǎng)景,基本上處處可見。
RestTemplate是一個(gè)執(zhí)行HTTP請(qǐng)求的同步阻塞式工具類,它僅僅只是在 HTTP 客戶端庫(kù)(例如 JDK HttpURLConnection,Apache HttpComponents,okHttp 等)基礎(chǔ)上,封裝了更加簡(jiǎn)單易用的模板方法 API,方便程序員利用已提供的模板方法發(fā)起網(wǎng)絡(luò)請(qǐng)求和處理,能很大程度上提升我們的開發(fā)效率
1、前置配置
在spring環(huán)境下使用RestTemplate
如果當(dāng)前項(xiàng)目是SpringBoot,添加SpringBoot啟動(dòng)依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>同時(shí),將RestTemplate配置初始化為一個(gè)Bean對(duì)象
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}注意:在這種初始化方法,是使用了JDK自帶的HttpURLConnection作為底層HTTP客戶端實(shí)現(xiàn)。
在需要使用RestTemplate的位置,注入并使用即可!
@Autowired private RestTemplate restTemplate;
2、API實(shí)戰(zhàn):
RestTemplate最大的特色就是對(duì)各種網(wǎng)絡(luò)請(qǐng)求方式做了包裝,能極大的簡(jiǎn)化開發(fā)人員的工作量,下面我們以GET、POST、PUT、DELETE為例,分別介紹各個(gè)API的使用方式
2.1 GET請(qǐng)求:
2.1.1 不帶參的get請(qǐng)求
@RestController
public class TestController {
/**
* 不帶參的get請(qǐng)求
* @return
*/
@RequestMapping(value = "testGet", method = RequestMethod.GET)
public User testGet(){
User user = new User();
user.setCode("200");
user.setMsg("請(qǐng)求成功,方法:testGet");
return user;
}
}
@Data
public class User {
private String code;
private String msg;
}@Autowired
private RestTemplate restTemplate;
/**
* 單元測(cè)試(不帶參的get請(qǐng)求)
*/
@Test
public void testGet(){
//請(qǐng)求地址
String url = "http://localhost:8080/testGet";
//發(fā)起請(qǐng)求,直接返回對(duì)象
User user = restTemplate.getForObject(url, User.class);
}2.1.2 帶參的get請(qǐng)求(使用占位符號(hào)傳參)
@RestController
public class TestController {
/**
* 帶參的get請(qǐng)求(restful風(fēng)格)
* @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("請(qǐng)求成功,方法:testGetByRestFul,請(qǐng)求參數(shù)id:" + id + "請(qǐng)求參數(shù)name:" + name);
return user;
}
}@Autowired
private RestTemplate restTemplate;
/**
* 單元測(cè)試(帶參的get請(qǐng)求)
*/
@Test
public void testGetByRestFul(){
//請(qǐng)求地址
String url = "http://localhost:8080/testGetByRestFul/{1}/{2}";
//發(fā)起請(qǐng)求,直接返回對(duì)象(restful風(fēng)格)
User user = restTemplate.getForObject(url, User.class, "001", "張三");
}2.1.3 帶參的get請(qǐng)求(restful風(fēng)格)
@RestController
public class TestController {
/**
* 帶參的get請(qǐng)求(restful風(fēng)格)
* @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("請(qǐng)求成功,方法:testGetByParam,請(qǐng)求參數(shù)userName:" + userName + ",userPwd:" + userPwd);
return user;
}
}@Autowired
private RestTemplate restTemplate;
/**
* 單元測(cè)試(帶參的get請(qǐng)求)
*/
@Test
public void testGetByParam(){
//請(qǐng)求地址
String url = "http://localhost:8080/testGetByParam?userName={userName}&userPwd={userPwd}";
//請(qǐng)求參數(shù)
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("userName", "唐三藏");
uriVariables.put("userPwd", "123456");
//發(fā)起請(qǐng)求,直接返回對(duì)象(帶參數(shù)請(qǐng)求)
User user = restTemplate.getForObject(url, User.class, uriVariables);
}2.1.4 getForEntity使用示例
上面的所有的getForObject請(qǐng)求傳參方法,getForEntity都可以使用,使用方法上也幾乎是一致的,只是在返回結(jié)果接收的時(shí)候略有差別。
使用ResponseEntity<T> responseEntity來接收響應(yīng)結(jié)果。用responseEntity.getBody()獲取響應(yīng)體。
/**
* 單元測(cè)試
*/
@Test
public void testAllGet(){
//請(qǐng)求地址
String url = "http://localhost:8080/testGet";
//發(fā)起請(qǐng)求,返回全部信息
ResponseEntity<User> response = restTemplate.getForEntity(url, User.class);
// 獲取響應(yīng)體
System.out.println("HTTP 響應(yīng)body:" + response.getBody().toString());
// 以下是getForEntity比getForObject多出來的內(nèi)容
HttpStatus statusCode = response.getStatusCode();
int statusCodeValue = response.getStatusCodeValue();
HttpHeaders headers = response.getHeaders();
System.out.println("HTTP 響應(yīng)狀態(tài):" + statusCode);
System.out.println("HTTP 響應(yīng)狀態(tài)碼:" + statusCodeValue);
System.out.println("HTTP Headers信息:" + headers);
}header設(shè)置參數(shù)
//請(qǐng)求頭
HttpHeaders headers = new HttpHeaders();
headers.add("token", "123456789");
//封裝請(qǐng)求頭
HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange('請(qǐng)求的url', HttpMethod.GET, formEntity, String.class);2.2 GET請(qǐng)求:
其實(shí)POST請(qǐng)求方法和GET請(qǐng)求方法上大同小異,RestTemplate的POST請(qǐng)求也包含兩個(gè)主要方法:
postForObject():返回body對(duì)象postForEntity():返回全部的信息
2.2.1 模擬表單請(qǐng)求
模擬表單請(qǐng)求,post方法測(cè)試
@RestController
public class TestController {
/**
* 模擬表單請(qǐng)求,post方法測(cè)試
* @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("請(qǐng)求成功,方法:testPostByForm,請(qǐng)求參數(shù)userName:" + userName + ",userPwd:" + userPwd);
return user;
}
}@Autowired
private RestTemplate restTemplate;
/**
* 模擬表單提交,post請(qǐng)求
*/
@Test
public void testPostByForm(){
//請(qǐng)求地址
String url = "http://localhost:8080/testPostByForm";
// 請(qǐng)求頭設(shè)置,x-www-form-urlencoded格式的數(shù)據(jù)
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//提交參數(shù)設(shè)置
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("userName", "唐三藏");
map.add("userPwd", "123456");
// 組裝請(qǐng)求體
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
//發(fā)起請(qǐng)求
User user = restTemplate.postForObject(url, request, User.class);
}2.2.2 模擬表單請(qǐng)求,post方法測(cè)試(接收對(duì)象)
@RestController
public class TestController {
/**
* 模擬表單請(qǐng)求,post方法測(cè)試
* @param request
* @return
*/
@RequestMapping(value = "testPostByFormAndObj", method = RequestMethod.POST)
public User testPostByForm(UserVO request){
User user = new User();
user.setCode("200");
user.setMsg("請(qǐng)求成功,方法:testPostByFormAndObj,請(qǐng)求參數(shù):" + JSON.toJSONString(request));
return user;
}
}
@Data
public class UserVO {
private String userName;
private String userPwd;
}@Autowired
private RestTemplate restTemplate;
/**
* 模擬表單提交,post請(qǐng)求
*/
@Test
public void testPostByForm(){
//請(qǐng)求地址
String url = "http://localhost:8080/testPostByFormAndObj";
// 請(qǐng)求頭設(shè)置,x-www-form-urlencoded格式的數(shù)據(jù)
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//提交參數(shù)設(shè)置
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("userName", "唐三藏");
map.add("userPwd", "123456");
// 組裝請(qǐng)求體
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
//發(fā)起請(qǐng)求
User user = restTemplate.postForObject(url, request, User.class);
}2.2.3 模擬JSON請(qǐng)求,post方法測(cè)試
@RestController
public class TestController {
/**
* 模擬JSON請(qǐng)求,post方法測(cè)試
* @param request
* @return
*/
@RequestMapping(value = "testPostByJson", method = RequestMethod.POST)
public User testPostByJson(@RequestBody UserVO request){
User user = new User();
user.setCode("200");
user.setMsg("請(qǐng)求成功,方法:testPostByJson,請(qǐng)求參數(shù):" + JSON.toJSONString(request));
return user;
}
}@Autowired
private RestTemplate restTemplate;
/**
* 模擬JSON提交,post請(qǐng)求
*/
@Test
public void testPostByJson(){
//請(qǐng)求地址
String url = "http://localhost:8080/testPostByJson";
//入?yún)?
UserVO vo = new UserVO();
vo.setUserName("唐三藏");
vo.setUserPwd("123456789");
//發(fā)送post請(qǐng)求,并打印結(jié)果,以String類型接收響應(yīng)結(jié)果JSON字符串
ResponseBean responseBean = restTemplate.postForObject(url, vo, User.class);
}2.3 PUT請(qǐng)求
put請(qǐng)求方法,可能很多人都沒用過,它指的是修改一個(gè)已經(jīng)存在的資源或者插入資源,該方法會(huì)向URL代表的資源發(fā)送一個(gè)HTTP PUT方法請(qǐng)求,示例如下
@RestController
public class TestController {
/**
* 模擬JSON請(qǐng)求,put方法測(cè)試
* @param request
* @return
*/
@RequestMapping(value = "testPutByJson", method = RequestMethod.PUT)
public void testPutByJson(@RequestBody UserVO request){
System.out.println("請(qǐng)求成功,方法:testPutByJson,請(qǐng)求參數(shù):" + JSON.toJSONString(request));
}
}@Autowired
private RestTemplate restTemplate;
/**
* 模擬JSON提交,put請(qǐng)求
*/
@Test
public void testPutByJson(){
//請(qǐng)求地址
String url = "http://localhost:8080/testPutByJson";
//入?yún)?
UserVO request = new UserVO();
request.setUserName("唐三藏");
request.setUserPwd("123456789");
//模擬JSON提交,put請(qǐng)求
restTemplate.put(url, request);
}2.4 DELETE請(qǐng)求
與之對(duì)應(yīng)的還有delete方法協(xié)議,表示刪除一個(gè)已經(jīng)存在的資源,該方法會(huì)向URL代表的資源發(fā)送一個(gè)HTTP DELETE方法請(qǐng)求。
@RestController
public class TestController {
/**
* 模擬JSON請(qǐng)求,delete方法測(cè)試
* @return
*/
@RequestMapping(value = "testDeleteByJson", method = RequestMethod.DELETE)
public void testDeleteByJson(){
System.out.println("請(qǐng)求成功,方法:testDeleteByJson");
}
}@Autowired
private RestTemplate restTemplate;
/**
* 模擬JSON提交,delete請(qǐng)求
*/
@Test
public void testDeleteByJson(){
//請(qǐng)求地址
String url = "http://localhost:8080/testDeleteByJson";
//模擬JSON提交,delete請(qǐng)求
restTemplate.delete(url);
}2.5 Exchange方法
如果以上方法還不滿足你的要求。在RestTemplate工具類里面,還有一個(gè)exchange通用協(xié)議請(qǐng)求方法,它可以發(fā)送GET、POST、DELETE、PUT、OPTIONS、PATCH等等HTTP方法請(qǐng)求。
到此這篇關(guān)于SpringBoot下使用RestTemplate實(shí)現(xiàn)遠(yuǎn)程服務(wù)調(diào)用的詳細(xì)過程的文章就介紹到這了,更多相關(guān)SpringBoot RestTemplate遠(yuǎn)程服務(wù)調(diào)用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot-RestTemplate實(shí)現(xiàn)調(diào)用第三方API的方式
- Springboot使用RestTemplate調(diào)用第三方接口的操作代碼
- SpringBoot 如何使用RestTemplate來調(diào)用接口
- SpringBoot-RestTemplate如何實(shí)現(xiàn)調(diào)用第三方API
- SpringBoot使用RestTemplate實(shí)現(xiàn)HTTP請(qǐng)求詳解
- springboot中RestTemplate配置HttpClient連接池詳解
- springboot集成RestTemplate及常見的用法說明
- Springboot之restTemplate的配置及使用方式
相關(guān)文章
Activiti如何動(dòng)態(tài)獲取流程圖過程詳解
這篇文章主要介紹了Activiti如何動(dòng)態(tài)獲取流程圖過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
IntelliJ IDEA本地代碼提交到github網(wǎng)站不顯示與本地不同步問題的解決辦法
今天小編就為大家分享一篇關(guān)于IntelliJ IDEA本地代碼提交到github網(wǎng)站不顯示與本地不同步問題的解決辦法,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-10-10
Java ZooKeeper分布式鎖實(shí)現(xiàn)圖解
ZooKeeper是一個(gè)分布式的,開放源碼的分布式應(yīng)用程序協(xié)調(diào)服務(wù),是Google的Chubby一個(gè)開源的實(shí)現(xiàn),是Hadoop和Hbase的重要組件。它是一個(gè)為分布式應(yīng)用提供一致性服務(wù)的軟件,提供的功能包括:配置維護(hù)、域名服務(wù)、分布式同步、組服務(wù)等2022-03-03
解決springboot3:mybatis-plus依賴錯(cuò)誤:org.springframework.beans.fac
這篇文章主要介紹了解決springboot3:mybatis-plus依賴錯(cuò)誤:org.springframework.beans.factory.UnsatisfiedDependencyException問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
Feign Client超時(shí)時(shí)間設(shè)置不生效的解決方法
這篇文章主要為大家詳細(xì)介紹了Feign Client 超時(shí)時(shí)間設(shè)置不生效的原因與解決方法,具有一定的的參考價(jià)值,希望對(duì)大家有一定的幫助2025-04-04
Java和JVM的重載識(shí)別,重寫方法是怎樣進(jìn)行的
這篇文章主要介紹了Java和JVM的重載識(shí)別,重寫方法是怎樣進(jìn)行的,違章圍繞了Java和JVM的重載識(shí)別,重寫方法展開相關(guān)資料,需要的小伙伴可以參考一下,希望對(duì)你的工作或?qū)W習(xí)有所幫助2022-01-01
Java基于websocket協(xié)議與netty實(shí)時(shí)視頻彈幕交互實(shí)現(xiàn)
本文主要介紹了Java基于websocket協(xié)議與netty實(shí)時(shí)視頻彈幕交互實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
IDEA中的Run/Debug Configurations各項(xiàng)解讀
這篇文章主要介紹了IDEA中的Run/Debug Configurations各項(xiàng)解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09

