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

浙公网安备 33010602011771号