springboot 2.0 整合 RestTemplate
首先导入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的更多相关文章
- SpringBoot 2.0 整合sharding-jdbc中间件,实现数据分库分表
一.水平分割 1.水平分库 1).概念: 以字段为依据,按照一定策略,将一个库中的数据拆分到多个库中. 2).结果 每个库的结构都一样:数据都不一样: 所有库的并集是全量数据: 2.水平分表 1).概 ...
- springboot 2.0 整合 同时支持jsp+html跳转
springboot项目创建教程 https://blog.csdn.net/q18771811872/article/details/88126835 springboot2.0 跳转html教程 ...
- SpringBoot 2.0整合阿里云OSS,实现动静分离架构
前言 相信大部分开发者对下面这张架构图并不陌生吧,现在很多网站/应用都采用了动静分离的架构进行部署.博主的博客也不例外,主机采用的是阿里云的 ECS,使用 CDN 做静态内容分发,不过静态文件还是存储 ...
- springboot 2.0+整合RabbitMQ
基于spring-boot 2.* 作用: 1.异步处理 2.应用解耦 3.流量削峰 相关概念介绍: Broker:它提供一种传输服务,它的角色就是维护一条从生产者到消费者的路线,保证数据能按照指 ...
- Springboot 2.0.4 整合Mybatis出现异常Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
在使用Springboot 2.0.4 整合Mybatis的时候出现异常Property 'sqlSessionFactory' or 'sqlSessionTemplate' are require ...
- 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 ...
- SpringBoot与Mybatis整合方式01(源码分析)
前言:入职新公司,SpringBoot和Mybatis都被封装了一次,光用而不知道原理实在受不了,于是开始恶补源码,由于刚开始比较浅,存属娱乐,大神勿喷. 就如网上的流传的SpringBoot与Myb ...
- Springboot security cas整合方案-实践篇
承接前文Springboot security cas整合方案-原理篇,请在理解原理的情况下再查看实践篇 maven环境 <dependency> <groupId>org.s ...
- springboot 与 shiro 整合 (简洁版)
前言: 网上有很多springboot 与 shiro 整合的资料,有些确实写得很好, 对学习shiro和springboot 都有很大的帮助. 有些朋友比较省事, 直接转发或者复制粘贴.但是没有经过 ...
随机推荐
- 软件测试跟踪工具Bugzilla的安装 - Linux版本
首先查看Linux当前版本 输入"uname -a ",可显示电脑以及操作系统的相关信息 输入"cat /proc/version",说明正在运行的内核版本 输 ...
- 详解递归(基础篇)———函数栈、阶乘、Fibonacci数列
一.递归的基本概念 递归函数:在定义的时候,自己调用了自己的函数. 注意:递归函数定义的时候一定要明确结束这个函数的条件! 二.函数栈 栈:一种数据结构,它仅允许栈顶进,栈顶出,先进后出,后进先出.我 ...
- PAT乙级:1053 住房空置率 (20分)
PAT乙级:1053 住房空置率 (20分) 题干 在不打扰居民的前提下,统计住房空置率的一种方法是根据每户用电量的连续变化规律进行判断.判断方法如下: 在观察期内,若存在超过一半的日子用电量低于某给 ...
- 关键字替代符号C++
不知从什么时候的哪里我看到了一个and关键字,心想这是个什么玩意...然后知道它相当于&&,于是开启了罪恶的生涯-- 替代关键字,似乎可读性更好,但是有些编译器可能会无法识别(eg.M ...
- 《Node+MongoDB+React 项目实战开发》已出版
前言 从深圳回长沙已经快4个月了,除了把车开熟练了外,并没有什么值得一提的,长沙这边要么就是连续下一个月雨,要么就是连续一个月高温暴晒,上班更是没啥子意思,长沙这边的公司和深圳落差挺大的,薪资也是断崖 ...
- 在 CentOS 7.5 64位上使用 yum 安装 MySQL 8.0
前段时间在 CentOS 7.5 64位上安装 MySQL 8.0.查了些资料,在这里记录一下详细的安装和设置步骤. 一.安装 使用yum安装MySQL之前需要先下载对应的.rpm文件,下载方法: 去 ...
- PHP 后台数组数据 传输给前台JS 使用
一. PHP: $a = array('aaa','bbb'); $a= json_encode($a); JS: var a_json = {$a}; //此处a_json数组便可使用 二. H ...
- PHP5.6.6上运行 ecshop 2.7.3常见问题处理
ecshop在在PHP5.6.6版本以后,有了很多细微的变化.而ECSHOP官方更新又太慢,发现这些问题后也不及时升级,导致用户安装使用过程中错误百出. 整理一下我遇到的问题希望对你们能有些帮组也为了 ...
- 抽奖动画 - lao虎机抽奖
本文介绍一个lao虎机抽奖动画的实现,lao虎机抽奖在各类商家营销活动中非常常见,这里主要介绍动画的实现过程,其他细节不做详细分析. ps:lao虎机是敏感词,博客园不允许出现,所有老用拼音. 1. ...
- 一些Shell脚本记录
查看换行符 使用vim打开文件,输入:set ff?.根据返回结果可以文件类型 字符串 opcenter.sjb.bz [root@opcenter backup]# echo ${HOSTNAME% ...