springboot 整合RestTemplate

1.RestTemplate

在项目中,当我们需要远程调用一个 HTTP 接口时,我们经常会用到 RestTemplate 这个类。这个类是 Spring 框架提供的一个工具类。Spring 框架提供的 RestTemplate 类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接,我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。

2.配置RestTemplateConfig

复制代码
 1 @Configuration 
2
public class RestTemplateConfig { 3 @Bean 4 public RestTemplate restTemplate(@Qualifier("simpleClientHttpRequestFactory") ClientHttpRequestFactory factory){ 5 return new RestTemplate(factory); 6 } 7 8 @Bean 9 public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ 10 SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); 11 factory.setConnectTimeout(15000); 12 // 获取数据超时时间 毫秒 13 factory.setReadTimeout(5000); 14 return factory; 15 } 16 17 }
复制代码

3.简单使用

复制代码
 1 @Log4j
 2 @Component
 3 public class RmsInterfaceUtils {
 4 
 5     @Autowired
 6     private RestTemplate restTemplate;
 7 
 8     public Response post(String url, RegisterDeviceRequest request) {
 9         log.info("调用接口: " + url);
10         //返回对象
11         Response response;
12         try {
13             response = restTemplate.postForObject(url, request, Response.class);
14         } catch (Exception e) {
15             log.error("RMS Server接口调用异常", e);
16             response = new Response();
17             response.setCode(1024);
18             response.setMsg("RMS Server接口调用异常");
19             response.setRequestId(request.getRequestId());
20         }
21         return response;
22     }
23 
24 }
复制代码

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

 

posted @   时间无岸  阅读(2360)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
点击右上角即可分享
微信分享提示