Spring RestTemplate说明

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 the Accept-Encoding header field, however RestTemplate 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.

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

实现该converter的converter, 可以从HTTP Requet和HTTP Response读取字节数组. 默认该converter支持读取所有的 media type , 并且以 application/octet-streamcontent-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 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 数据, 并且以 application/octet-strem 的格式写数据.

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/* 数据, 并且以 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 , 在使用时, 只选择一个即可. 如果两个都有配置, 可能会出现问题.

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.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容