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 都有很大的帮助. 有些朋友比较省事, 直接转发或者复制粘贴.但是没有经过 ...
随机推荐
- java测试银行系统源代码
1 package Kaoshi; 2 3 /*信1705-3 20173442 田昕可*/ 4 import java.util.*; 5 import java.io.*; 6 7 class A ...
- Java基础00-学生管理系统16
1. 学生管理系统 1.1 项目演示 1.2 实现思路 1.3 定义学生类 public class Student { private String sid; private String name ...
- 【Mysql】InnoDB 引擎中的数据页结构
InnoDB 是 mysql 的默认引擎,也是我们最常用的,所以基于 InnoDB,学习页结构.而学习页结构,是为了更好的学习索引. 一.页的简介 页是 InnoDB 管理存储空间的基本单位,一个页的 ...
- python编程面试题
# 实现需求为 注册.登录.查看昵称的功能 # def userN(): # username = input("请输入账号: \n") # password = ...
- 【分布式锁】通过MySQL数据库的表来实现-V1
一.来源 之所以要写这篇文章是因为想对自己当前的分布式知识做一个归纳.今天就先推出一篇MySQL实现的分布式锁,后续会继续推出其他版本的分布式锁,比如通过Zookeeper.Redis实现等. 二.正 ...
- HCNA Routing&Switching之OSPF度量值和基础配置命令总结
前文我们了解了OSPF的网络类型,OSPF中的DR和BDR的选举规则.作用等相关话题,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/15054938.html: ...
- chcod炸弹
[题目描述] 话说Cpp国和Pas国发生了战争, Pas国派出了强大的飞机战队, Cpp国于是使出了炸弹CHCOD 来反击Pas国的飞机舰队.然而CHCOD的发射器,只能逐渐往上打.所以Cpp国现在只 ...
- npm WARN checkPermissions Missing write access to ......解决方法
npm安装出错 npm WARN checkPermissions Missing write access to ...... 解决方法: 删除本地node_modules文件夹,之后再次 npm ...
- vue3.0使用ant-design-vue进行按需加载原来这么简单
下载 ui库 yarn add ant-design-vue 默认是全局引入,打包后体积很大, 非常影响首屏加载速度, 按需加载 下载按需加载的插件;推荐使用cnpm cnpm install bab ...
- 第二十一篇 -- QTimer实现秒表功能
效果图: 程序一开始就开始计时,当完成了相关功能(在线程中完成)之后,就触发停止信号,停止定时器. time.py #!/usr/bin/env python # _*_ coding: UTF-8 ...