简介:
spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接,我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。
RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过setRequestFactory方法替换为例如Apache HttpComponents、Netty或OkHttp等其它HTTP library。
其实spring并没有真正的去实现底层的http请求(3次握手),而是集成了别的http请求,spring只是在原有的各种http请求进行了规范标准,让开发者更加简单易用,底层默认用的是jdk的http请求。
RestTemplate的优缺点:
优点:
连接池、超时时间设置、支持异步、请求和响应的编解码
缺点:
依赖别的spring版块、参数传递不灵活
springboot集成RestTemplate:
1.导入依赖:(其实他是spring集成好的,这个一般的springboot项目已经由此包了)
org.springframework.boot
spring-boot-starter-web
2.把 RestTemplate交给spring管理
package com.rails.travel.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* RestTemplate配置类
*/
@Configuration
public class RestTemplateConfig {
//最好是用不注释的方法,在注入的同时设置连接时间,这种注释的也可以,但是没有设置超时时间
/*@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}*/
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);//单位为ms
factory.setConnectTimeout(5000);//单位为ms
return factory;
}
}
3.引用:(其实他是可以直接使用的,不需要配置任何东西依赖都可以不引)
@Autowired
private RestTemplate restTemplate;//这样就可以直接调用api使用了或者直接new对象也一样
RestTemplate主要的6个方法:
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
至此就可以直接调用API使用了,具体的调用及原理,连接池配置等可以参考如下收集的几个很棒的文章
需要注意的是参数一定要用map否则接受的时候会有“null”这种情况而不是null
RestTemplate官方网站:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html
很好的介绍文章: https://www.xncoding.com/2017/07/06/spring/sb-restclient.html
http://ju.outofmemory.cn/entry/341530
https://my.oschina.net/lifany/blog/688889
关于配置http连接池原理的文章:
https://blog.csdn.net/umke888/article/details/54881946
https://www.cnblogs.com/likaitai/p/5431246.html