首页 技术 正文
技术 2022年11月19日
0 收藏 519 点赞 3,343 浏览 6256 个字

什么是RestTemplate?

RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求,可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。
ClientHttpRequestFactory接口主要提供了两种实现方式

  • 一种是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)创建底层的Http请求连接。
  • 一种方式是使用HttpComponentsClientHttpRequestFactory方式,底层使用HttpClient访问远程的Http服务,使用HttpClient可以配置连接池和证书等信息。

RestTemplate默认是使用SimpleClientHttpRequestFactory,内部是调用jdk的HttpConnection,默认超时为-1

基于jdk的spring的RestTemplate

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byName" default-lazy-init="true"> <!--方式一、使用jdk的实现--> <bean id="ky.requestFactory" class="org.springframework.http.client.SimpleClientHttpRequestFactory"> <property name="readTimeout" value="10000"/> <property name="connectTimeout" value="5000"/> </bean> <bean id="simpleRestTemplate" class="org.springframework.web.client.RestTemplate"> <constructor-arg ref="ky.requestFactory"/> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.FormHttpMessageConverter"/> <bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter"/> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean></beans>

使用Httpclient连接池的方式(推荐)

<!--使用httpclient的实现,带连接池--><!--在httpclient4.3版本后才有--><bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create">    <property name="connectionManager">        <bean class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">            <!--整个连接池的并发-->            <property name="maxTotal" value="50"/>            <!--每个主机的并发-->            <property name="defaultMaxPerRoute" value="50"/>        </bean>    </property>    <!--开启重试-->    <property name="retryHandler">        <bean class="org.apache.http.impl.client.DefaultHttpRequestRetryHandler">            <constructor-arg value="2"/>            <constructor-arg value="true"/>        </bean>    </property>    <property name="defaultHeaders">        <list>            <bean class="org.apache.http.message.BasicHeader">                <constructor-arg value="Content-Type"/>                <constructor-arg value="text/html;charset=UTF-8"/>            </bean>            <bean class="org.apache.http.message.BasicHeader">                <constructor-arg value="Accept-Encoding"/>                <constructor-arg value="gzip,deflate"/>            </bean>            <bean class="org.apache.http.message.BasicHeader">                <constructor-arg value="Accept-Language"/>                <constructor-arg value="zh-CN"/>            </bean>        </list>    </property></bean><bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build"/><bean id="restTemplate" class="org.springframework.web.client.RestTemplate">    <property name="messageConverters">        <list value-type="org.springframework.http.converter.HttpMessageConverter">            <bean class="org.springframework.http.converter.StringHttpMessageConverter">                <property name="supportedMediaTypes">                    <value>text/html;charset=UTF-8</value>                </property>            </bean>            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">                <property name="supportedMediaTypes">                    <value>application/json;charset=UTF-8</value>                </property>            </bean>            <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>            <bean class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter"/>            <bean class="org.springframework.http.converter.FormHttpMessageConverter"/>            <bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter"/>        </list>    </property>    <property name="requestFactory">        <bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">            <constructor-arg ref="httpClient"/>            <!--连接时间(毫秒)-->            <property name="connectTimeout" value="20000"/>            <!--读取时间(毫秒)-->            <property name="readTimeout" value="20000"/>        </bean>    </property></bean>

初体验(POST)

package com.winner.rest;import com.alibaba.fastjson.JSON;import org.springframework.beans.factory.annotation.Value;import org.springframework.http.HttpEntity;import org.springframework.http.HttpHeaders;import org.springframework.http.MediaType;import org.springframework.stereotype.Service;import org.springframework.web.client.RestTemplate;import javax.annotation.Resource;import java.io.UnsupportedEncodingException;/** * Created by winner_0715 on 2017/1/7. */@Servicepublic class TestGet {    @Resource    private RestTemplate restTemplate;    /**     * 要请求的url,一般放在配置文件中     */    @Value(value = "@{remote.url}")    private String remoteUrl;    public String postRemoteData(ParameterRo ro) throws UnsupportedEncodingException {        /**         * 设置请求头         */        HttpHeaders headers = new HttpHeaders();        headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));        headers.add("Accept", MediaType.APPLICATION_JSON.toString());        /**         * POST请求参数,根据需要进行封装         */        String bodyData = new String(Base64Util.encodeData(JSON.toJSONString(ro)).getBytes("UTF-8"), "UTF-8");        /**         * 查看HttpEntity的构造方法,包含只有请求头和只有请求体的情况         */        HttpEntity<String> httpEntity = new HttpEntity<String>(bodyData, headers);        /**         * 执行操作         */        String result = restTemplate.postForObject(remoteUrl, httpEntity, String.class);        return result;    }    /**     * 模拟请求参数     */    private class ParameterRo {        private Integer id = 123;        public Integer getId() {            return id;        }        public void setId(Integer id) {            this.id = id;        }    }}

初体验(GET)

package com.winner.rest;import com.alibaba.fastjson.JSON;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import org.springframework.web.client.RestTemplate;import javax.annotation.Resource;import java.io.UnsupportedEncodingException;/** * Created by winner_0715 on 2017/1/7. */@Servicepublic class TestGet {    @Resource    private RestTemplate restTemplate;    /**     * 要请求的url,一般放在配置文件中     */    @Value(value = "@{remote.url}")    private String remoteUrl;    public String getRemoteData(ParameterRo ro) throws UnsupportedEncodingException {        //根据需要也可以设置请求头        /**         * get请求参数,根据需要进行封装(加密等)         */        String getData = new String(Base64Util.encodeData(JSON.toJSONString(ro)).getBytes("UTF-8"), "UTF-8");        /**         * 执行操作         */        String result = restTemplate.getForObject(remoteUrl + "?" + getData, String.class);        return result;    }    /**     * 模拟请求参数     */    private class ParameterRo {        private Integer id = 123;        public Integer getId() {            return id;        }        public void setId(Integer id) {            this.id = id;        }    }}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,087
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,562
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,412
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,185
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,821
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905