一、RestTemplate使用:
1、基本使用:
1.1、引用依赖
org.springframework
spring-web
${spring.version}
org.springframework
spring-webmvc
${spring.version}
1.2、定义基本RestTemplate
或者
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(1500000);
factory.setConnectTimeout(50000);
return factory;
}
}
1.3、通过RestTemplate 执行http调用:
方法说明:
第一种和第二种的首个参数都是用String表示一个URI。但它们的最后一个参数分别是Object[]和Map
第三种的首个参数使用java.net.URI表示一个URI。且只有两个参数
这是因为,String类型的URI支持占位符。比如:
restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}",String.class,"42", "21");
那么最终访问的URI为:http://example.com/hotels/42/bookings/21
但是String有一个小缺陷:String形式的URI会被URL编码两次(URL encode请自行百度),这就要求服务器在获取URI中的参数时主动进行一次解码,但如果服务的提供者不这么做呢?
这时就需要使用不会使用任何编码的java.net.URI
常用的就是POST 和 GET:
public T getForObject(String url, Class responseType, Object... uriVariables) throws RestClientException
public ResponseEntity getForEntity(String url, Class responseType, Object... uriVariables)
public T postForObject(String url, @Nullable Object request, Class responseType,
Object... uriVariables) throws RestClientException
public ResponseEntity postForEntity(String url, @Nullable Object request,
Class responseType, Object... uriVariables) throws RestClientException
ForObject 和 ForEntity 有什么区别?
ForEntity 对应响应 ResponseEntity 封装了响应状态信息、响应头信息以及响应体,getForObject直接返回响应体。
常见使用场景:
1、请求带header:
POST:
@Override
public ResponseEntity postForEntity(String url, @Nullable Object request,
Class responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
ResponseExtractor> responseExtractor = responseEntityExtractor(responseType);
return nonNull(execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables));
}
请求参数封装header 信息
Object request :
HttpHeaders headers = new HttpHeaders();
this.getConfigs.getRsaHeader().forEach((k, v) -> {
headers.add(k, v);
});
headers.add("apigwkey", *****);
httpEntity = new HttpEntity(GsonUtil.toJsonString(rq), headers);
或者通过exchange:
HttpHeaders headers = new HttpHeaders();
headers.add("token", "123");
ResponseEntity response = restTemplate.exchange(
"http://127.0.0.1:8280/user/{id}",
HttpMethod.GET,
new HttpEntity(headers),
UserBean.class,
userId);
2.扩展RestTemplate
RestTemplate发送http 功能包调整:
自定义http 实现
RestTemplate支持自定义http client 实现:
通过ClientHttpRequestFactory 产生http 请求:
默认:采用jdk 的httpurlconnnect
private ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
SimpleClientHttpRequestFactory(封装URLConnection) //默认
HttpComponentsClientHttpRequestFactory(封装HttpClient)
OkHttp3ClientHttpRequestFactory(封装OKHttp)
如何扩展:
比如说我用apache 的httpclient来实现:
1、引入依赖
org.apache.httpcomponents
httpclient
4.5.7
2、定义ClientHttpRequestFactory
自定义响应解析
请求如何序列化以及响应如何反序列化
static {
ClassLoader classLoader = RestTemplate.class.getClassLoader();
romePresent = ClassUtils.isPresent("com.rometools.rome.feed.WireFeed", classLoader);
jaxb2Present = ClassUtils.isPresent("javax.xml.bind.Binder", classLoader);
jackson2Present =
ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
jackson2XmlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", classLoader);
jackson2SmilePresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader);
jackson2CborPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.cbor.CBORFactory", classLoader);
gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader);
jsonbPresent = ClassUtils.isPresent("javax.json.bind.Jsonb", classLoader);
}
通过类加载器判断有没有对应的jar
public RestTemplate() {
this.messageConverters.add(new ByteArrayHttpMessageConverter());
this.messageConverters.add(new StringHttpMessageConverter());
this.messageConverters.add(new ResourceHttpMessageConverter(false));
try {
this.messageConverters.add(new SourceHttpMessageConverter<>());
}
catch (Error err) {
// Ignore when no TransformerFactory implementation is available
}
this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
if (romePresent) {
this.messageConverters.add(new AtomFeedHttpMessageConverter());
this.messageConverters.add(new RssChannelHttpMessageConverter());
}
if (jackson2XmlPresent) {
this.messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
}
else if (jaxb2Present) {
this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
}
if (jackson2Present) {
this.messageConverters.add(new MappingJackson2HttpMessageConverter());
}
else if (gsonPresent) {
this.messageConverters.add(new GsonHttpMessageConverter());
}
else if (jsonbPresent) {
this.messageConverters.add(new JsonbHttpMessageConverter());
}
if (jackson2SmilePresent) {
this.messageConverters.add(new MappingJackson2SmileHttpMessageConverter());
}
if (jackson2CborPresent) {
this.messageConverters.add(new MappingJackson2CborHttpMessageConverter());
}
this.uriTemplateHandler = initUriTemplateHandler();
}
默认会添加很多消息转换器,用户序列化和反序列化
ResponseExtractor:
该接口有三个实现类:
HeadersExtractor | 用于提取请求头。 |
---|---|
HttpMessageConverterExtractor | 用于提取响应body。 |
ResponseEntityResponseExtractor | 使用HttpMessageConverterExtractor提取body(委托模式),然后将body和响应头、状态封装成ResponseEntity对象。 |
提取器HttpMessageConverterExtractor寻找可用的转化器
在默认的RestTemplate的构造函数中初始化了转化器集合,包括:
转化器 | 可转化的类型 |
---|---|
ByteArrayHttpMessageConverter | byte[] |
StringHttpMessageConverter | String |
ResourceHttpMessageConverter | Resource |
SourceHttpMessageConverter | javax.xml.transform.* |
AllEncompassingFormHttpMessageConverter | MultiValueMap |
Jaxb2RootElementHttpMessageConverter | XmlRootElement,XmlType(注解) |
... | |
MappingJackson2HttpMessageConverter | Json |
通常使用时会采用常用的Jsong 工具包:
比如说GSON 、Jackson 等等
if (jackson2Present) {
this.messageConverters.add(new MappingJackson2HttpMessageConverter());
}
else if (gsonPresent) {
this.messageConverters.add(new GsonHttpMessageConverter());
}
else if (jsonbPresent) {
this.messageConverters.add(new JsonbHttpMessageConverter());
}
如果添加了Jackson 依赖 ,那么jackson2Present 会为true,添加了GSON ,gsonPresent 会为true