RestTemplate发送远程请求
restTemplate
是spring
提供的可以提供访问rest服务的客户端工具类,提供多种快捷的访问远程的方法,大大提高了客户端的编程效率。解放了原先HttpClient
的复杂提交。
借助 RestTemplate
,Spring
应用能够方便地使用REST资源,Spring
的 RestTemplate
访问使用了模版方法的设计模式。
模版方法将过程中与特定实现相关的部分委托给接口,而这个接口的不同实现定义了接口的不同行为。
RestTemplate定义了36个与REST资源交互的方法,其中的大多数都对应于HTTP的方法。
其实,这里面只有11个独立的方法,其中有十个有三种重载形式,而第十一个则重载了六次,这样一共形成了36个方法。
delete() 在特定的URL上对资源执行HTTP DELETE操作exchange()
在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中
映射得到的execute() 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象
postForEntity()
POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得
到的postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象
headForHeaders() 发送HTTP HEAD请求,返回包含特定资源URL的HTTP头
optionsForAllow() 发送HTTP OPTIONS请求,返回对特定URL的Allow头信息
postForLocation() POST 数据到一个URL,返回新创建资源的URL
put() PUT 资源到特定的URL
也就是两种请求,get
请求和post
请求。
一,get
请求
1,getForObject
用法
消费者发起请求
/**
* @title
* @description get请求 getForObject用法
* @author FanJiangFeng
* @updateTime 2019/12/9 15:32
* @throws
*/
@RequestMapping("/go")
@ResponseBody
public String studyHttp(){
String url="http://127.0.0.1:8082/demoTest?name={name}&email={email}";
Map<String,String> map=new HashMap<String, String>();
map.put("name","樊江锋");
map.put("email","675361896@qq.com");
RestTemplate restTemplate=new RestTemplate();
String response = restTemplate.getForObject(url, String.class, map);
log.info("response:"+response);
//[nio-8088-exec-1] com.example.controller.HttpController : response:success
return response;
}
提供者接收并响应请求
/**
* @title
* @description get请求 getForObject用法
* @author FanJiangFeng
* @updateTime 2019/12/9 15:32
* @throws
*/
@RequestMapping(value = "demoTest", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String demoTest(@RequestParam String name,@RequestParam String email){
System.out.println(name);
System.out.println(email);
return "success";
}
2,getForEntity
用法
消费者发起请求
/**
* @title
* @description get请求 getForEntity用法
* @author FanJiangFeng
* @updateTime 2019/12/11 16:19
* @throws
*/
@RequestMapping("/getTest")
@ResponseBody
public String getTest(){
String url="http://127.0.0.1:8082/demoTest1?name={name}&email={email}";
// HttpHeaders headers=new HttpHeaders();
// headers.set("phone","123456");
Map<String,Object> map=new HashMap<String, Object>();
map.put("name","樊江锋");
map.put("email","675361896@qq.com");
RestTemplate restTemplate = new RestTemplate();
// HttpEntity httpEntity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.getForEntity(url,String.class,map);
log.info("response:"+response.getBody());
String body = response.getBody();
return body;
}
提供者接收并响应请求
/**
* @title
* @description get请求 getForEntity用法
* @author FanJiangFeng
* @updateTime 2019/12/11 16:19
* @throws
*/
@GetMapping(value = "demoTest1", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String demoTest1(@RequestParam String name, @RequestParam String email){
System.out.println(name);
System.out.println(email);
return "success";
}
二,post
请求
当所有传递的数据类型为复杂数据类型headers.setContentType(MediaType.MULTIPART_FORM_DATA
并且需要接受的参数不再实体类中进行映射。MultiValueMap
来进行传递。
消费者发起请求
/**
* @title
* @description post请求
* @author FanJiangFeng
* @updateTime 2019/12/11 16:39
* @throws
*/
@RequestMapping("/getTest1")
@ResponseBody
public String getTest1(){
String url="http://127.0.0.1:8082/demoTest2";
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.APPLICATION_JSON);
// headers.set("phone", "123456");
//传参数可以使用map,也可以使用user
//如果使用map,下面postForEntity要改成Map类型;postForEntity(url, map,String.class);
// Map<String,Object> map=new HashMap<String, Object>();
// map.put("name","樊江锋");
// map.put("email","675361896@qq.com");
// 如果使用user对象,要改成user对象 postForEntity(url, user,String.class);
// User user=new User();
// user.setName("袁梦阳");
// user.setEmail("test@qq.com");
//当所有传递的数据类型为复杂数据类型,并且需要接受的参数不再实体类中进行映射。MultiValueMap来进行传递。
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("name", "袁梦阳");
params.add("email", "675361896@qq.com");
RestTemplate restTemplate = new RestTemplate();
//HttpEntity用来装载请求头或者MultiValueMap集合(参数)
// HttpEntity httpEntity = new HttpEntity(params,headers);
ResponseEntity<String> request = restTemplate.postForEntity(url,params,String.class);
System.out.println(request.getBody());
return request.getBody();
}
提供者接收并响应请求
/**
* @title
* @description post请求
* @author FanJiangFeng
* @updateTime 2019/12/11 16:39
* @throws
* //post请求 如果client参数是MultiValueMap传递,需要去掉consumes = MediaType.APPLICATION_JSON_VALUE
*/
@RequestMapping(value = "demoTest2",produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody //如果client参数是对象,则括号中为 @RequestBody User user 如果是MultiValueMap,则括号中为 @RequestParam String name,@RequestParam String email
public String demoTest2(@RequestParam String name,@RequestParam String email){
// System.out.println(user.getName());
// System.out.println(user.getEmail());
System.out.println(name);
System.out.println(email);
return "success";
}
三,综合示例
可以参考下方的RestTemplate
的例子发送远程请求。
发送方
/**
* @Description 发送远程请求,进入投标保险首页
* @Date 2019/12/16 15:57
* @return
* @Author FanJiangFeng
* @Version1.0
* @History
*/
public String sendPostReq(String requestData) throws IOException {
RestTemplate restTemplate = new RestTemplate();
String url = "http://127.0.0.1:7000/tbbx/insurance/enter";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("requestData",requestData);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
String responseData = response.getBody();
return responseData;
}
接收方
/**
* @title
* @description 招采平台进入本平台入口
* @author FanJiangFeng
* @updateTime 2019/12/10 15:59
* @throws
*/
@RequestMapping(value = "/enter",produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String test(@RequestParam String requestData) throws Exception {
JSONObject jsonObject = JSONObject.parseObject(requestData);
String APPID=(String) jsonObject.get("APPID");
String encryptParam=(String) jsonObject.get("encryptParam");
String signature=(String) jsonObject.get("signature");
//返回json串数据
JSONObject map=new JSONObject();
map.put("status",1000);
map.put("message","连接成功");
String jsonString = JSONObject.toJSONString(map);
return jsonString;
}
顺利请求并反馈信息流程成功!
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~