RestTemplate内置的几个功能
1. HTTP Client
当创建一个 RestTemplate
对象的时候, RestTemplate
可以选择两种 Http client
.
- 一种是
J2SE
标准的Http client
- 一种是
HttpComponents HttpClient
J2SE
标准的 Http Client
通过 SimpleClientHttpRequestFactory
创建.
HttpComponents HttpClient
配置自定义的Http Client Factory
通过 setRequestFactory(ClientHttpRequestFactory requestFactory)
可以配置 Http Client Factory
.
SimpleClientHttpRequestFactory
设置超时时间
simpleClientHttpRequestFactory.setConnectTimeout(millions);
simpleClientHttpRequestFactory.setReadTimeout(millions);
2. Gzip Compression
RestTemplate
supports sending and receiving data encoded with gzip compression. The HTTP specification allows for additional values in theAccept-Encoding
header field, howeverRestTemplate
only supports gzip compression at this time.
HTTP协议支持通过在请求头增加 Accept-Encoding
来支持多种压缩方式.
但是目前 RestTemplate
只支持 GZIP
压缩 .
3. Object与JSON转换
4. Object与XML转换
Content-Type 配置
HttpMessageConverter
主要作用:
RestTemplate's behavior is customized by providing callback methods and configuring the
HttpMessageConverter
used to marshal objects into the HTTP request body and to unmarshal any response back into an object.
- 将Java对象序列化到
Request Body
中, 注意, 这里是Request Body
中, 不是在Params中 - 将
Response
的任意返回结果, 转换成一个Java对象. 这里不限制返回的类型
当创建RestTemplate时, 默认注册的Message Converter有 ByteArrayHttpMessageConverter
, StringHttpMessageConverter
, ResourceHttpMessageConverter
, SourceHttpMessageConverter
, AllEncompassingFormHttpMessageConverter
.
并且可以根据是否有加载相关的类, 来自动注册相关的Message Converter.
Table 2.1. Default Message Converters
Message Body Converter | Inclusion Rule |
---|---|
ByteArrayHttpMessageConverter |
Always included |
StringHttpMessageConverter |
Always included |
ResourceHttpMessageConverter |
Always included |
SourceHttpMessageConverter |
Always included |
AllEncompassingFormHttpMessageConverter |
Always included |
SimpleXmlHttpMessageConverter |
Included if the Simple XML serializer is present. |
MappingJackson2HttpMessageConverter |
Included if the Jackson 2.x JSON processor is present. |
GsonHttpMessageConverter |
Included if Gson is present. Jackson 2.x takes precedence over Gson if both are available on the classpath. |
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);
}
/**
* Create a new instance of the {@link RestTemplate} using default settings.
* Default {@link HttpMessageConverter HttpMessageConverters} are initialized.
*/
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();
}
所有的Converter都有一个默认的 Media Type
, 并且可以通过重写 supportedMediaTypes
来更改支持的 Media Type
类型.
ByteArrayHttpMessageConverter
An
HttpMessageConverter
implementation that can read and write byte arrays from the HTTP request and response. By default, this converter supports all media types (*/*
), and writes with aContent-Type
ofapplication/octet-stream
. This can be overridden by setting the supportedMediaTypes property, and overridinggetContentType(byte[])
.
实现该converter的converter, 可以从HTTP Requet和HTTP Response读取字节数组. 默认该converter支持读取所有的 media type
, 并且以 application/octet-stream
的 content-type
类型写入数据.
该converter可以通过设置 supportedMedia
属性和重写 getContentType(byte[])
方法更改上述行为.
FormHttpMessageConverter
An
HttpMessageConverter
implementation that can read and write form data from the HTTP request and response. By default, this converter reads and writes the media typeapplication/x-www-form-urlencoded
. Form data is read from and written into aMultiValueMap<String, String>
.
该converter支持 application/x-www-form-urlencoded
.
AllEncompassingFormHttpMessageConverter
Extension of
FormHttpMessageConverter
, adding support for XML and JSON-based parts.
该converter是对 FormHttpMessageConverter
的扩展, 用于支持XML和JSON
ResourceHttpMessageConverter
An
HttpMessageConverter
implementation that can read and writeResource
Resources. By default, this converter can read all media types. Written resources useapplication/octet-stream
for theContent-Type
.
该converter可以读取所有的 media type
数据, 并且以 application/octet-strem
的格式写数据.
SourceHttpMessageConverter
An
HttpMessageConverter
implementation that can read and writejavax.xml.transform.Source
from the HTTP request and response. OnlyDOMSource
,SAXSource
, andStreamSource
are supported. By default, this converter supportstext/xml
andapplication/xml
.
该converter支持读写 text/xml
, application/xml
StringHttpMessageConverter
An
HttpMessageConverter
implementation that can read and write Strings from the HTTP request and response. By default, this converter supports all text media types (text/*
), and writes with aContent-Type
oftext/plain
.
该converter支持读取所有的 text/*
数据, 并且以 text/plain
格式写回.
SimpleXmlHttpMessageConverter
An
HttpMessageConverter
implementation that can read and write XML from the HTTP request and response using Simple Framework'sSerializer
. XML mapping can be customized as needed through the use of Simple's provided annotations. When additional control is needed, a customSerializer
can be injected through theSerializer
property. By default, this converter reads and writes the media typesapplication/xml
,text/xml
, andapplication/*+xml
.
MappingJackson2HttpMessageConverter
An
HttpMessageConverter
implementation that can read and write JSON using Jackson (2.x)'sObjectMapper
. JSON mapping can be customized as needed through the use of Jackson's provided annotations. When further control is needed, a customObjectMapper
can be injected through theObjectMapper
property for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supportsapplication/json
.Please note that this message converter and the
GsonHttpMessageConverter
both supportapplication/json
by default. Because of this, you should only add one JSON message converter to aRestTemplate
instance.RestTemplate
will use the first converter it finds that matches the specified mime type, so including both could produce unintended results.
该converter支持 application/json
的读写.
该converter与 GsonHttpMessageConverter
都用于 application/json
, 在使用时, 只选择一个即可. 如果两个都有配置, 可能会出现问题.
GsonHttpMessageConverter
An
HttpMessageConverter
implementation that can read and write JSON using Google Gson'sGson
class. JSON mapping can be customized as needed through the use of Gson's provided annotations. When further control is needed, a customGson
can be injected through theGson
property for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supportsapplication/json
.