什么是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. scala安装

    一:在官网下载相应的版本http://www.scala-lang.org/download/2.10.6.html 二,在linux中解压下载下来的scala包   三:配置环境变量 export ...

  2. 7.Java中的字符串

    1.String的特性 特性一:不可变性 String s=new String("yangyun") s=s.toUpperCase(); 这里的s,s占用的空间是不一样的(地址 ...

  3. SQL数字转英文函数

    -- 数字转英文 -- ============================================= -- Author: qianjin036a -- Create date:06/1 ...

  4. Android入门(二):Android工程目录结构

    首先我们来看看Android工程的目录结构,如下图: 下面我们来看看每个文件夹都是用来做什么的? 1.src:这个不用多说,它就是保存Java源文件的目录: 2.gen:该文件夹用来保存自动生成的R. ...

  5. InstallShield制作升级安装包

    1. 在General Information里,修改Product Version为新的版本号,此版本号应大于旧的版本号.点击Product Code右面的{...},获取一个新的Product C ...

  6. easyui datalist按组多选

    结果如下: 数据样式如下: [ {"text":"Epson WorkForce 845","group":"Printer&qu ...

  7. 【听说是线段树】bzoj1012 [JSOI2008]最大数maxnumber

    一眼看题目吓了一跳:这TM不就是单调队列吗,200000又怎样,大不了我二分嘛 系统提示:成功开启 手残模式 开始瞎写: #include <cstdio> ]; ]; int m,mod ...

  8. springboot+dubbo之多端口注入服务

    前面介绍了,springboot+dubbo基础整合,这篇介绍多端口注入服务. springboot使用@Bean注入dubbo服务,当你是单一的ProviderConfig实例,dubbo的@Ser ...

  9. mysql event_scheduler运行一段时间后 自动关闭

    应该是你重启过电脑或重启过服务了.  SELECT * FROM mysql.event;SET GLOBAL event_scheduler = 1; -- 开启定时器 0:off 1:on SHO ...

  10. navicat使用

      navicat我觉得做程序的基本上都会用,它方便,快捷,直观等,优点很多,这也是我写这篇文章的原因.以前我基本上都是用phpmyadmin,也挺好用,不过也有不少缺点,比如数据库备份文件太大,根本 ...