首先导入springboot 的 web 包

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

restTemplateBuilder的方式被废弃,就推荐使用。

@Configuration
public class AppConfig
{
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder)
{
return restTemplateBuilder
.setConnectTimeout(...)
.setReadTimeout(...)
.build();
}
}

在启动类同包下创建RestTemplate.java类:

2.0之后的方法,可以通过SimpleClientHttpRequestFactory来设置

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate; import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List; /**
* @author wangcanfeng
* @time 2019/3/6
* @function 远程调用rest接口客户端注册
**/
@Configuration
public class RestTemplateAutoConfiguration {
//连接超时时间
@Value("${rest.connection.timeout}")
private Integer connectionTimeout;
// 信息读取超时时间
@Value("${rest.read.timeout}")
private Integer readTimeout; /**
* 功能描述:注册restTemplate服务
*
* @param
* @author wangcanfeng
* @time 2019/3/6 20:26
* @since v1.0
**/ @Bean
public RestTemplate registerTemplate() {
RestTemplate restTemplate = new RestTemplate(getFactory());
//这个地方需要配置消息转换器,不然收到消息后转换会出现异常
restTemplate.setMessageConverters(getConverts());
return restTemplate;
} /**
* 功能描述: 初始化请求工厂
*
* @param
* @author wangcanfeng
* @time 2019/3/6 20:27
* @since v1.0
**/
private SimpleClientHttpRequestFactory getFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(connectionTimeout);
factory.setReadTimeout(readTimeout);
return factory;
} /**
* 功能描述: 设置数据转换器,我再这里只设置了String转换器
*
* @param
* @author wangcanfeng
* @time 2019/3/6 20:32
* @since v1.0
**/
private List<HttpMessageConverter<?>> getConverts() {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
// String转换器
StringHttpMessageConverter stringConvert = new StringHttpMessageConverter();
List<MediaType> stringMediaTypes = new ArrayList<MediaType>() {{
//配置text/plain和text/html类型的数据都转成String
add(new MediaType("text", "plain", Charset.forName("UTF-8")));
add(MediaType.TEXT_HTML);
}};
stringConvert.setSupportedMediaTypes(stringMediaTypes);
messageConverters.add(stringConvert);
return messageConverters;
}
}

然后在Service类中注入使用即可

@Service
public class demoService { @Autowired
private RestTemplate restTemplate; public String get(Integer id){
return restTemplate.getForObject("http://localhost:8080/user?userId=id",String.class);
}
}

RestTemplate定义了36个与REST资源交互的方法,其中的大多数都对应于HTTP的方法。 
其实,这里面只有11个独立的方法,其中有十个有三种重载形式,而第十一个则重载了六次,这样一共形成了36个方法。

  • delete() 在特定的URL上对资源执行HTTP DELETE操作
  • exchange() 在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中映射得到的
  • execute() 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
  • getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
  • getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象
  • postForEntity() POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的
  • postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象
  • headForHeaders() 发送HTTP HEAD请求,返回包含特定资源URL的HTTP头
  • optionsForAllow() 发送HTTP OPTIONS请求,返回对特定URL的Allow头信息
  • postForLocation() POST 数据到一个URL,返回新创建资源的URL
  • put() PUT 资源到特定的URL

getForEntity

get请求就和正常在浏览器url上发送请求一样

下面是有参数的get请求

    @GetMapping("getForEntity/{id}")
public User getById(@PathVariable(name = "id") String id) {
ResponseEntity<User> response = restTemplate.getForEntity("http://localhost/get/{id}", User.class, id);
User user = response.getBody();
return user;
}

getForObject

getForObject 和 getForEntity 用法几乎相同,指示返回值返回的是 响应体,省去了我们 再去 getBody()

    @GetMapping("getForObject/{id}")
public User getById(@PathVariable(name = "id") String id) {
User user = restTemplate.getForObject("http://localhost/get/{id}", User.class, id);
return user;
}

postForEntity

    @RequestMapping("saveUser")
public String save(User user) {
ResponseEntity<String> response = restTemplate.postForEntity("http://localhost/save", user, String.class);
String body = response.getBody();
return body;
}

postForObject

用法与 getForObject 一样

如果遇到 postForObject 方法在 Controller 接受不到参数问题 请参考的的另一篇博客 :

https://www.cnblogs.com/deityjian/p/12513377.html

exchange

@PostMapping("demo")
public void demo(Integer id, String name){ HttpHeaders headers = new HttpHeaders();//header参数
headers.add("authorization",Auth);
headers.setContentType(MediaType.APPLICATION_JSON); JSONObject obj = new JSONObject();//放入body中的json参数
obj.put("userId", id);
obj.put("name", name); HttpEntity<JSONObject> request = new HttpEntity<>(content,headers); //组装 ResponseEntity<String> response = template.exchange("http://localhost:8080/demo",HttpMethod.POST,request,String.class);
}

springboot2.0 RestTemplate,get,post,put,delete设置请求header示例

package smartt.styy.auth.util;
import java.net.URI;
import java.nio.charset.Charset;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder; @Component
public class ExternalCallUtils { //统一,认证服务接口调用post
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String restRequest(Object reqParam,Boolean needHeader,String Headers,HttpMethod method, String url) throws Exception{
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//设置token值
if(needHeader) {
headers.add("Authorization", Headers);
}
RequestEntity request = null ;
if(null != reqParam) {
request = new RequestEntity(reqParam,headers, method, new URI(url));
}else {
request = new RequestEntity(headers, method, new URI(url));
} RestTemplate rest =new RestTemplate();
ResponseEntity<String> resp = rest.exchange(request, new ParameterizedTypeReference<String>(){});
System.out.println("resp status:"+resp.getStatusCode());
if(resp.getStatusCode()!=null && resp.getStatusCodeValue() ==200) {
return resp.getBody();
}
} catch (Exception e) {
throw new Exception("认证服务失败!");
}
return null;
} //put delete ,obj为请求实体,转json
public static <T> T restPutRequest(Object obj, String url,String token, HttpMethod method, Class<T> bodyType) throws Exception{ // 请求头
HttpHeaders headers = new HttpHeaders();
MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
// 请求体
headers.setContentType(mediaType);
//提供json转化功能
//ObjectMapper mapper = new ObjectMapper(); if(!StringUtils.isEmpty(token)){
headers.add("Authorization", token);
} String jsonStr = JSONObject.toJSONString(obj);
// 发送请求
HttpEntity<String> entity = new HttpEntity<>(jsonStr, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<T> resultEntity = restTemplate.exchange(url, method, entity, bodyType);
return resultEntity.getBody();
} //get
public static <T> T restGetRequest(Class<T> bodyType,String url,String token, HttpMethod method) throws Exception{
HttpHeaders headers = new HttpHeaders();
MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
// 请求体
headers.setContentType(mediaType);
//提供json转化功能
//ObjectMapper mapper = new ObjectMapper(); if(!StringUtils.isEmpty(token)){
headers.add("Authorization", token);
} HttpEntity<String> entity = new HttpEntity<>(null, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<T> resultEntity = restTemplate.exchange(url,method,entity,bodyType);
return resultEntity.getBody(); } }

springboot 2.0 整合 RestTemplate的更多相关文章

  1. SpringBoot 2.0 整合sharding-jdbc中间件,实现数据分库分表

    一.水平分割 1.水平分库 1).概念: 以字段为依据,按照一定策略,将一个库中的数据拆分到多个库中. 2).结果 每个库的结构都一样:数据都不一样: 所有库的并集是全量数据: 2.水平分表 1).概 ...

  2. springboot 2.0 整合 同时支持jsp+html跳转

    springboot项目创建教程 https://blog.csdn.net/q18771811872/article/details/88126835 springboot2.0 跳转html教程  ...

  3. SpringBoot 2.0整合阿里云OSS,实现动静分离架构

    前言 相信大部分开发者对下面这张架构图并不陌生吧,现在很多网站/应用都采用了动静分离的架构进行部署.博主的博客也不例外,主机采用的是阿里云的 ECS,使用 CDN 做静态内容分发,不过静态文件还是存储 ...

  4. springboot 2.0+整合RabbitMQ

    基于spring-boot 2.* 作用: 1.异步处理 2.应用解耦 3.流量削峰   相关概念介绍: Broker:它提供一种传输服务,它的角色就是维护一条从生产者到消费者的路线,保证数据能按照指 ...

  5. Springboot 2.0.4 整合Mybatis出现异常Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required

    在使用Springboot 2.0.4 整合Mybatis的时候出现异常Property 'sqlSessionFactory' or 'sqlSessionTemplate' are require ...

  6. SpringBoot(2.0.4.RELEASE)+Elasticsearch(6.2.4)+Gradle简单整合

    记录一下SpringBoot(2.0.4.RELEASE)+Elasticsearch(6.2.4)+Gradle整合的一个小例子. 1.在Gradle内加入相关jar包的依赖: compile('o ...

  7. SpringBoot与Mybatis整合方式01(源码分析)

    前言:入职新公司,SpringBoot和Mybatis都被封装了一次,光用而不知道原理实在受不了,于是开始恶补源码,由于刚开始比较浅,存属娱乐,大神勿喷. 就如网上的流传的SpringBoot与Myb ...

  8. Springboot security cas整合方案-实践篇

    承接前文Springboot security cas整合方案-原理篇,请在理解原理的情况下再查看实践篇 maven环境 <dependency> <groupId>org.s ...

  9. springboot 与 shiro 整合 (简洁版)

    前言: 网上有很多springboot 与 shiro 整合的资料,有些确实写得很好, 对学习shiro和springboot 都有很大的帮助. 有些朋友比较省事, 直接转发或者复制粘贴.但是没有经过 ...

随机推荐

  1. Jmeter之事务控制器

    性能测试的结果统计时我们一定会关注TPS,TPS代表的是每秒事务数,每个事务对应的是我们的请求.虽然JMeter能够帮我们把每个请求统计成一个事务,但有时候我们希望把多个操作统计成一个事务,JMete ...

  2. CF466D题解

    思路: 我们首先处理出每个位子需要被多少个区间覆盖才能变成 \(h\) .即 $a_i=h-a_i $ 同时设定 \(b\) 序列为 \(a\) 序列的差分系列 如果 \(b_i==1\) ,很显然, ...

  3. 牛客OI测试赛2

    题目链接:https://www.nowcoder.com/acm/contest/185#question A.无序组数 暴力求出A和B的因子,注意二元组是无序的,因此还要考虑有些因子在A和B中都存 ...

  4. 【剑指offer】73.数组中出现次数超过一半的数字

    73.数组中出现次数超过一半的数字 知识点:数组:哈希:占领地思想: 题目描述 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字.例如输入一个长度为9的数组{1,2,3,2,2,2,5,4 ...

  5. airodump-ng的使用及显示

    PWR   表示所接收的信号的强度.表示为负数,数值赿大表示信号赿强.(绝对值赿大,数据赿值小) beacons  表示网卡接收到的AP发出的信号个数

  6. 一行代码让matplotlib图表变高大上

    1 简介 matplotlib作为Python生态中最流行的数据可视化框架,虽然功能非常强大,但默认样式比较简陋,想要制作具有简洁商务风格的图表往往需要编写众多的代码来调整各种参数. 而今天要为大家介 ...

  7. Linux CentOS 7 安装配置vsftp

    学习Linux时间不长,首次安装了vsftp,按照网上的各种帖子尝试配置,不过都没打到预期,不是被拒绝连接,就是连接超时,总之就是各种问题啊.当然了,不是别人配置的不对,而是自己不是太懂Linux,选 ...

  8. 本地项目的npm安装方法

    有些node项目如一些工具类的项目,安装以后通过命令行执行其功能.但是而对于本地自建的项目如何通过npm安装,然后通过命令行(项目定义了命令行)工具执行命令调用其功能呢? 对于这种情况,笔者主要通过两 ...

  9. Pb代理工具之mitmproxy

    mitmproxy 一 . mitmproxy介绍 mitmproxy 就是用于 MITM 的 proxy,MITM 即中间人攻击(Man-in-the-middle attack). 不同于 fid ...

  10. proteus8.1 pro 中文版安装破解教程

    Proteus8 Pro是非常有名的EDA工具(仿真软件),从原理图布图.代码调试到单片机与外围电路协同仿真,一键切换到PCB设计,真正实现了从概念到产品的完整设计.是唯一将电路仿真软件.PCB设计软 ...