RestTemplate內(nèi)置的幾個功能
1. HTTP Client
當創(chuàng)建一個 RestTemplate 對象的時候, RestTemplate 可以選擇兩種 Http client .
- 一種是
J2SE標準的Http client - 一種是
HttpComponents HttpClient
J2SE 標準的 Http Client 通過 SimpleClientHttpRequestFactory 創(chuàng)建.
HttpComponents HttpClient
配置自定義的Http Client Factory
通過 setRequestFactory(ClientHttpRequestFactory requestFactory) 可以配置 Http Client Factory .
SimpleClientHttpRequestFactory
設(shè)置超時時間
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協(xié)議支持通過在請求頭增加 Accept-Encoding 來支持多種壓縮方式.
但是目前 RestTemplate 只支持 GZIP 壓縮 .
3. Object與JSON轉(zhuǎn)換
4. Object與XML轉(zhuǎn)換
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的任意返回結(jié)果, 轉(zhuǎn)換成一個Java對象. 這里不限制返回的類型
當創(chuàng)建RestTemplate時, 默認注冊的Message Converter有 ByteArrayHttpMessageConverter , StringHttpMessageConverter , ResourceHttpMessageConverter , SourceHttpMessageConverter , AllEncompassingFormHttpMessageConverter .
并且可以根據(jù)是否有加載相關(guān)的類, 來自動注冊相關(guān)的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[]).
實現(xiàn)該converter的converter, 可以從HTTP Requet和HTTP Response讀取字節(jié)數(shù)組. 默認該converter支持讀取所有的 media type , 并且以 application/octet-stream 的 content-type 類型寫入數(shù)據(jù).
該converter可以通過設(shè)置 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 數(shù)據(jù), 并且以 application/octet-strem 的格式寫數(shù)據(jù).
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/* 數(shù)據(jù), 并且以 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 , 在使用時, 只選擇一個即可. 如果兩個都有配置, 可能會出現(xiàn)問題.
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.