什么是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. eclipse远程连接hive

    创建项目,添加jar包,hive的s上,所以也需要hadoop的一些jar 这个图片是从网上找的,我直接使用的以前hadoop的项目   创建测试类,写测试代码 //获取jdbc链接 private ...

  2. win7修改护眼色

    一. 手动修改 记得qq管家有一个功能就是护眼模式 那如何不通过第三方软件修复系统护眼色呢.百度后我在此记录下: 1.在桌面右键单击,选择“个性化”,在下面找到如图所示,点击进去 2.高级外观设置 3 ...

  3. 使用SQL Server Analysis Services数据挖掘的关联规则实现商品推荐功能(七)

    假如你有一个购物类的网站,那么你如何给你的客户来推荐产品呢?这个功能在很多电商类网站都有,那么,通过SQL Server Analysis Services的数据挖掘功能,你也可以轻松的来构建类似的功 ...

  4. ASP.NET Web API 提升性能的方法实践

    ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...

  5. java打包文件夹为zip文件

    //待压缩的文件目录 String sourceFile=sourceFilePath+"\\"+userName; //存放压缩文件的目录 String zipFilePath ...

  6. inline-block 兼容性

    inline-block 兼容性 通常网页模板都需要动态添加或删除内容,在做网页导航的时候,需要nav中的ul能够居中并实现自适应拓展,如果ul是固定的长度很好实现居中,只需要设置margin:0 a ...

  7. 从零开始山寨Caffe·零:必先利其器

    工作环境 巧妇有了米炊 众所周知,Caffe是在Linux下写的,所以长久以来,大家都认为跑Caffe,先装Linux. niuzhiheng大神发起了caffe-windows项目(解决了一些编译. ...

  8. css input[type=file] 样式美化,input上传按钮美化

    css input[type=file] 样式美化,input上传按钮美化 参考:http://www.haorooms.com/post/css_input_uploadmh

  9. Jmeter性能测试 入门

    Jmeter是一款优秀的开源测试工具, 是每个资深测试工程师,必须掌握的测试工具,熟练使用Jmeter能大大提高工作效率. 熟练使用Jmeter后, 能用Jmeter搞定的事情,你就不会使用LoadR ...

  10. HDU 1392 凸包模板题,求凸包周长

    1.HDU 1392 Surround the Trees 2.题意:就是求凸包周长 3.总结:第一次做计算几何,没办法,还是看了大牛的博客 #include<iostream> #inc ...