一、RestTemplate怎么引入和使用

在pom.xml文件中加入如下dependency:

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

在项目的config文件夹下创建InitBeanConfig.java,添加如下代码:

1 @Bean
2 public RestTemplate getRestTemplate() {
3 return new RestTemplate();
4 }

使用的方式很简单,如下:

1 @Autowired
2 private RestTemplate restTemplate;

二、给RestTemplate设置全局Header

在config文件夹下创建HeaderRequestInterceptor.java

 1 import org.springframework.http.HttpRequest;
2 import org.springframework.http.MediaType;
3 import org.springframework.http.client.ClientHttpRequestExecution;
4 import org.springframework.http.client.ClientHttpRequestInterceptor;
5 import org.springframework.http.client.ClientHttpResponse;
6
7 import java.io.IOException;
8
9 /**
10 * @author 远猷
11 * @version 1.0.0
12 * @copyright xxx.com
13 * @description RestTemplate拦截器统一添加请求头
14 * @create 2021-04-29 17:40:34
15 */
16 public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {
17 @Override
18 public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
19 httpRequest.getHeaders().setContentType(MediaType.APPLICATION_JSON);
20 httpRequest.getHeaders().set("Http-Rpc-Type", "JsonContent");
21 httpRequest.getHeaders().set("Http-Rpc-Timeout", "3000");
22 httpRequest.getHeaders().set("app-name", "xxxx");
23 return clientHttpRequestExecution.execute(httpRequest, bytes);
24 }
25 }

在InitBeanConfig的代码中加入

1 @Bean
2 public RestTemplate getRestTemplate() {
3 RestTemplate restTemplate = new RestTemplate();
4 //给所有的Http请求加上请求头
5 restTemplate.setInterceptors(Collections.singletonList(new HeaderRequestInterceptor()));
6 return restTemplate;
7 }

三、对RestTemplate进行错误处理

在config文件夹下创建RestTemplateErrorHandler.java

 1 import org.springframework.http.client.ClientHttpResponse;
2 import org.springframework.stereotype.Component;
3 import org.springframework.web.client.ResponseErrorHandler;
4
5 import java.io.IOException;
6
7 /**
8 * @author 远猷
9 * @version 1.0.0
10 * @copyright xxx.com
11 * @description 请求过程日志打印
12 * @create 2021-04-29 20:48:22
13 */
14 @Component
15 public class RestTemplateErrorHandler implements ResponseErrorHandler {
16
17 @Override
18 public boolean hasError(ClientHttpResponse response) throws IOException {
19 // 返回false表示不管response的status是多少都返回没有错
20 // 这里可以自己定义那些status code你认为是可以抛Error
21 return false;
22 }
23
24 @Override
25 public void handleError(ClientHttpResponse response) throws IOException {
26 // 这里面可以实现你自己遇到了Error进行合理的处理
27 System.out.println("handleError" + response);
28 }
29 }

在InitBeanConfig的代码中加入

1 @Bean
2 public RestTemplate getRestTemplate() {
3 RestTemplate restTemplate = new RestTemplate();
4 //给所有的Http请求加上请求头
5 restTemplate.setInterceptors(Collections.singletonList(new HeaderRequestInterceptor()));
6 //给请求的返回值加上自己的业务处理
7 restTemplate.setErrorHandler(new RestTemplateErrorHandler());
8 return restTemplate;
9 }

四、给RestTemplate的Get设置RequestBody参数

RestTemplate支持通过setRequestFactory设置HTTP请求客户端工具,支持jdk、httpclient、okHttp等,默认使用的是SimpleClientHttpRequestFactory,该工程使用的JDK实现,底层使用OutputStream来传递body数据,不支持GET传递body。

我们可以修改为httpclient,只需要使用HttpComponentsClientHttpRequestFactory,但是默认的httpclient的GET请求也是不支持传递body的。有两个用于定义Http请求的基础抽象类:HttpRequestBase、HttpEntityEnclosingRequestBase,前者扩展的不能传递body,而后者可以。引入httpClient依赖:

1 <dependency>
2 <groupId>org.apache.httpcomponents</groupId
3 <artifactId>httpclient</artifactId>
4 <version>4.5.13</version>
5 </dependency>

在config文件夹下创建HttpComponentsClientRestfulHttpRequestFactory.java

 1 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
2 import org.apache.http.client.methods.HttpUriRequest;
3 import org.springframework.http.HttpMethod;
4 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
5 import org.springframework.stereotype.Component;
6
7 import java.net.URI;
8
9 /**
10 * @author 远猷
11 * @version 1.0.0
12 * @copyright xxx.com
13 * @description 让RestTemplate的GET请求支持RequestBody参数
14 * @create 2021-04-30 09:26:15
15 */
16 @Component
17 public class HttpComponentsClientRestfulHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {
18 @Override
19 protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
20
21 if (httpMethod == HttpMethod.GET) {
22 return new HttpGetRequestWithEntity(uri);
23 }
24 return super.createHttpUriRequest(httpMethod, uri);
25 }
26
27 /**
28 * 定义HttpGetRequestWithEntity实现HttpEntityEnclosingRequestBase抽象类,以支持GET请求携带body数据
29 */
30 private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
31 public HttpGetRequestWithEntity(final URI uri) {
32 super.setURI(uri);
33 }
34
35 @Override
36 public String getMethod() {
37 return HttpMethod.GET.name();
38
39 }
40 }
41 }

在InitBeanConfig的代码中加入

 1 @Bean
2 public RestTemplate getRestTemplate() {
3 RestTemplate restTemplate = new RestTemplate();
4 //给所有的Http请求加上请求头
5 restTemplate.setInterceptors(Collections.singletonList(new HeaderRequestInterceptor()));
6 //给请求的返回值加上自己的业务处理
7 restTemplate.setErrorHandler(new RestTemplateErrorHandler());
8 //给RestTemplate的get请求加上RequestBody
9 restTemplate.setRequestFactory(new HttpComponentsClientRestfulHttpRequestFactory());
10 return restTemplate;
11 }

调用方式

1 String requestBody = "param"
2 restTemplate.exchange(url, HttpMethod.GET, new HttpEntity(requestBody, null), Object.class)

RestTemplate的一些坑和改造点的更多相关文章

  1. springcloud-03-服务注册

    新建一个 provider-user 和consumer-movie, user为服务提供者, movie为服务的消费真, 没有什么难的, 直接上代码 microserver-provider-use ...

  2. 分布式改造剧集之Redis缓存采坑记

    Redis缓存采坑记 ​ 前言 ​ 这个其实应该属于分布式改造剧集中的一集(第一集见前面博客:http://www.cnblogs.com/Kidezyq/p/8748961.html),本来按照顺序 ...

  3. RestTemplate踩坑 之 ContentType 自动添加字符集

    写在前边 最近在写 OAuth2 对接的代码,由于授权服务器(竹云BambooCloud IAM)部署在甲方内网,所以想着自己 Mock 一下授权方的返回体,验证一下我的代码.我这才踩到了坑-- 故事 ...

  4. 海豚调度5月Meetup:6个月重构大数据平台,帮你避开调度升级改造/集群迁移踩过的坑

    当今许多企业都有着技术架构的DataOps程度不够.二次开发成本高.迁移成本高.集群部署混乱等情况,团队在技术选型之后发现并不适合自己的需求,但是迁移成本和难度又比较大,甚至前团队还留下了不少坑,企业 ...

  5. shop++改造之ResponseEntity的坑

    后台shop++购物车请求的数据是一个Map结构的数据,业务需要要在类似的购物车中加一个套餐. 那么套餐里面就包含商品信息了,觉得不用他的Map了于是封装了两个类: 套餐信息显示类,商品信息显示类 请 ...

  6. Spring Cloud ZooKeeper集成Feign的坑1,错误:Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.

    错误如下: ERROR 31473 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** A ...

  7. springcloud-alibaba手写负载均衡的坑,采用restTemplate,不能添加@loadbalanced注解,否则采用了robbin

    采用springcloud-alibaba整合rabbion使用DiscoveryClient调用restful时遇到的一个问题,报错如下: D:\javaDevlepTool\java1.8\jdk ...

  8. springMvc改造springboot2.0踩坑

    1. 支持jsp applicaiton.proerties添加配置 #指定视图解析路径前缀 spring.mvc.view.prefix=/WEB-INF/jsp/ #指定视图解析后缀 spring ...

  9. H5嵌入原生开发小结----兼容安卓与ios的填坑之路

    一开始听说开发H5,以为就是做适配现代浏览器的移动网页,心想不用管IE了,欧也.到今天,发现当初too young too simple,兼容IE和兼容安卓与IOS,后者让你更抓狂.接下来数一下踩过的 ...

  10. ReactJS webpack实现JS模块化使用的坑

    从一个原生HTML/CSS/JS模式的网页改造到ReactJS模块化的结构,需要以下步骤: (1)引用ReactJS框架 ->(2)使用webpack 工具 -> (3)配置webpack ...

随机推荐

  1. [转帖]MySQL Decimal 的实现方法

    码: 背景 数字运算在数据库中是很常见的需求, 例如计算数量.重量.价格等, 为了满足各种需求, 数据库系统通常支持精准的数字类型和近似的数字类型. 精准的数字类型包含 int, decimal 等, ...

  2. [转帖]SpecCPU2017 测试cpu性能

    https://www.bbsmax.com/A/GBJrxP1Ed0/ SpecCPU介绍见: https://blog.csdn.net/qq_36287943/article/details/1 ...

  3. [转帖]kubelet 原理解析三:runtime

    本文转自:https://feisky.xyz/posts/kube... 架构 Kubelet 架构图 Generic Runtime Manager:这是容器运行时的管理者,负责于 CRI 交互, ...

  4. [转帖]HotSpot 虚拟机对象探秘

    https://www.cnblogs.com/xiaojiesir/p/15593092.html 对象的创建 一个对象创建的时候,到底是在堆上分配,还是在栈上分配呢?这和两个方面有关:对象的类型和 ...

  5. Nginx的Keepalive的简单学习

    摘要 最近发现某项目的Nginx负载服务器上面有很多Time_wait的TCP连接 可以使用命令 netstat -n |awk '/^tcp/ {++S[$NF]} END{for (a in S) ...

  6. 初识VUE响应式原理

    作者:京东零售 吴静 自从Vue发布以来,就受到了广大开发人员的青睐,提到Vue,我们首先想到的就是Vue的响应式系统,那响应式系统到底是怎么回事呢?接下来我就给大家简单介绍一下Vue中的响应式原理. ...

  7. Vue基础系列文章10---单文件组件

    1.单文件组件的结构 <template> <!--这里用于定义VUE组件的模块内容--> <dvi> <h1>这是 APP 根组件</h1> ...

  8. iphone(ios)不同设备的内存和游戏不闪退峰值

    ios内存限制 不同内存的苹果机型上(1G,2G,3G,4G-),游戏内存的峰值一般最高多少能保证不闪退? 一般来讲最保险的就是不超过机器总内存的50%,具体每个机型的内存限制在列出在下面. 原贴:& ...

  9. 从零开始配置vim(28)——DAP 配置

    首先给大家说一声抱歉,前段时间一直在忙换工作的事,包括但不限于交接.背面试题准备面试.好在最终找到了工作,也顺利入职了.期间也有朋友在催更,在这里我对关注本系列的朋友表示感谢.多的就不说了,我们正式进 ...

  10. gRPC学习小札

    gRPC 前言 为什么使用gRPC 传输协议 传输效率 性能消耗 gRPC入门 gRPC流 证书认证 使用根证书 gRPC实现token认证 和Web服务共存 验证器 REST接口 grpcurl工具 ...