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
RestTemplatesupports sending and receiving data encoded with gzip compression. The HTTP specification allows for additional values in theAccept-Encodingheader field, howeverRestTemplateonly 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
HttpMessageConverterused 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
HttpMessageConverterimplementation 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-Typeofapplication/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
HttpMessageConverterimplementation 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
HttpMessageConverterimplementation that can read and writeResourceResources. By default, this converter can read all media types. Written resources useapplication/octet-streamfor theContent-Type.
该converter可以读取所有的 media type 数据, 并且以 application/octet-strem 的格式写数据.
SourceHttpMessageConverter
An
HttpMessageConverterimplementation that can read and writejavax.xml.transform.Sourcefrom the HTTP request and response. OnlyDOMSource,SAXSource, andStreamSourceare supported. By default, this converter supportstext/xmlandapplication/xml.
该converter支持读写 text/xml , application/xml
StringHttpMessageConverter
An
HttpMessageConverterimplementation 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-Typeoftext/plain.
该converter支持读取所有的 text/* 数据, 并且以 text/plain 格式写回.
SimpleXmlHttpMessageConverter
An
HttpMessageConverterimplementation 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 customSerializercan be injected through theSerializerproperty. By default, this converter reads and writes the media typesapplication/xml,text/xml, andapplication/*+xml.
MappingJackson2HttpMessageConverter
An
HttpMessageConverterimplementation 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 customObjectMappercan be injected through theObjectMapperproperty 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
GsonHttpMessageConverterboth supportapplication/jsonby default. Because of this, you should only add one JSON message converter to aRestTemplateinstance.RestTemplatewill 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
HttpMessageConverterimplementation that can read and write JSON using Google Gson'sGsonclass. JSON mapping can be customized as needed through the use of Gson's provided annotations. When further control is needed, a customGsoncan be injected through theGsonproperty for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supportsapplication/json.