什么是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.
 */
@Service
public 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.
 */
@Service
public 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;
        }
    }
}

RestTemplate配置的更多相关文章

  1. 使用RestTemplate Spring安全认证

    使用RestTemplate Spring安全认证 java spring 认证authentication 安全spring-security 我有提供2个独立的一整套服务2 Spring的web应 ...

  2. RestTemplate post如何传递参数

    背景 今天跟同事接口联调,使用RestTemplate请求服务端的post接口(使用python开发).诡异的是,post请求,返回500 Internal Server Error,而使用get请求 ...

  3. spring boot / cloud (八) 使用RestTemplate来构建远程调用服务

    spring boot / cloud (八) 使用RestTemplate来构建远程调用服务 前言 上周因家里突发急事,请假一周,故博客没有正常更新 RestTemplate介绍: RestTemp ...

  4. SpringCloud系列五:Ribbon 负载均衡(Ribbon 基本使用、Ribbon 负载均衡、自定义 Ribbon 配置、禁用 Eureka 实现 Ribbon 调用)

    1.概念:Ribbon 负载均衡 2.具体内容 现在所有的服务已经通过了 Eureka 进行了注册,那么使用 Eureka 注册的目的是希望所有的服务都统一归属到 Eureka 之中进 行处理,但是现 ...

  5. RestTemplate发送HTTP、HTTPS请求

    RestTemplate 使用总结   场景: 认证服务器需要有个 http client 把前端发来的请求转发到 backend service, 然后把 backend service 的结果再返 ...

  6. Springboot 使用 RestTemplate

    每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code spring web 项目提供的RestTemplate,使java访问url更方便, ...

  7. 使用HttpClient4来构建Spring RestTemplate

    Spring RestTemplate简单说明 现在REST服务已经很普及了,在我们的程序中,经常会需要调用REST API,这时候会有很多选择,原始一点的JDK自带的,再进一步点使用HttpClie ...

  8. spring的RestTemplate使用指南

    前言:现在restful接口越来越广泛,而如今很多接口摒弃了传统的配置复杂的webService开发模式,在java领域只需要很简单的springMvc就可以声明为一个控制器,再加上service层, ...

  9. SpringBoot中使用RestTemplate

    spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可 ...

随机推荐

  1. 开发Visual Studio 插件

    新建项目,在其他项目类型中找到扩展性,然后新建Visual Studio外接程序,VS中没有这个要安装SDK,http://yunpan.cn/cd27eNczKREwd (提取码:ab29)去下载 ...

  2. Linux下安装JDK多种方式

    一.环境说明: 操作系统:Linux xx- -.el6.x86_64 # SMP Thu Jul :: UTC x86_64 x86_64 x86_64 GNU/Linux jdk版本:java-- ...

  3. eclipse运行速度优化(解决狂读盘、发布慢、CPU100%等问题)

    转自:http://blog.csdn.net/wyp_810618/article/details/8953921 我的ECLIPSE运行时速度奇慢,具体表现为: 1.只要ECLIPSE启动后,硬盘 ...

  4. 在visual studio2015中使用easyX画图

    配置:解压EasyX压缩包: 将文件内的include,lib,lib/amd64下的文件拷贝到visualstudio中VC文件夹内对应的地方: 然后再执行上图中的Setup.hta进行安装: 在v ...

  5. 《DSP using MATLAB》示例Example5.7

    代码: x = [1, 1, 1, 1, zeros(1,4)]; N = 8; % zero-padding operation X_DFT = dft(x,N); % DFT of x(n) ma ...

  6. 【TYVJ1864】[Poetize I]守卫者的挑战 概率与期望

    [TYVJ1864][Poetize I]守卫者的挑战 描述 打开了黑魔法师Vani的大门,队员们在迷宫般的路上漫无目的地搜寻着关押applepi的监狱的所在地.突然,眼前一道亮光闪过."我 ...

  7. C#读写配置文件

    .net有两种程序,一个是web程序,另外一种是app客户端程序,这两种程序的配置文件读写模式不同,web程序是直接读写马上生效.app客户端程序比如刷新加载一次. System.Configurat ...

  8. 利用OTP为odoo增强安全访问

    两次验证是广泛应用于各大站点的验证机制,我们今天利用Google Authentication来实现Odoo的两次验证,防止撞库或密码泄露等引起的安全问题. 1. 二次验证的原理 参见 http:// ...

  9. Vue.js组件之联动下拉框

    Html代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...

  10. JavaScript电子时钟+倒计时

    JavaScript时间类      获取时分秒:          getHours()          getMinutes();          getSeconds();       获取 ...