Spring RestTemplate說明

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

RestTemplate supports sending and receiving data encoded with gzip compression. The HTTP specification allows for additional values in the Accept-Encoding header field, however RestTemplate only 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 HttpMessageConverter used to marshal objects into the HTTP request body and to unmarshal any response back into an object.

  1. 將Java對象序列化到 Request Body 中, 注意, 這里是 Request Body 中, 不是在Params中
  2. 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 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 a Content-Type of application/octet-stream. This can be overridden by setting the supportedMediaTypes property, and overriding getContentType(byte[]).

實現(xiàn)該converter的converter, 可以從HTTP Requet和HTTP Response讀取字節(jié)數(shù)組. 默認該converter支持讀取所有的 media type , 并且以 application/octet-streamcontent-type 類型寫入數(shù)據(jù).

該converter可以通過設(shè)置 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 type application/x-www-form-urlencoded. Form data is read from and written into a MultiValueMap<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 write Resource Resources. By default, this converter can read all media types. Written resources use application/octet-stream for the Content-Type.

該converter可以讀取所有的 media type 數(shù)據(jù), 并且以 application/octet-strem 的格式寫數(shù)據(jù).

SourceHttpMessageConverter

An HttpMessageConverter implementation that can read and write javax.xml.transform.Source from the HTTP request and response. Only DOMSource, SAXSource, and StreamSource are supported. By default, this converter supports text/xml and application/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 a Content-Type of text/plain.

該converter支持讀取所有的 text/* 數(shù)據(jù), 并且以 text/plain 格式寫回.

SimpleXmlHttpMessageConverter

An HttpMessageConverter implementation that can read and write XML from the HTTP request and response using Simple Framework's Serializer. XML mapping can be customized as needed through the use of Simple's provided annotations. When additional control is needed, a custom Serializer can be injected through the Serializer property. By default, this converter reads and writes the media types application/xml, text/xml, and application/*+xml.

MappingJackson2HttpMessageConverter

An HttpMessageConverter implementation that can read and write JSON using Jackson (2.x)'s ObjectMapper. JSON mapping can be customized as needed through the use of Jackson's provided annotations. When further control is needed, a custom ObjectMapper can be injected through the ObjectMapper property for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supports application/json.

Please note that this message converter and the GsonHttpMessageConverter both support application/json by default. Because of this, you should only add one JSON message converter to a RestTemplate 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 , 在使用時, 只選擇一個即可. 如果兩個都有配置, 可能會出現(xiàn)問題.

GsonHttpMessageConverter

An HttpMessageConverter implementation that can read and write JSON using Google Gson's Gson class. JSON mapping can be customized as needed through the use of Gson's provided annotations. When further control is needed, a custom Gson can be injected through the Gson property for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supports application/json.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容