简介

RestTemplat是Spring3.0开始提供的http请求的工具,提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率,RestTemplate 是一个同步的 Rest API 客户端;

创建RestTemplat

通过SimpleClientHttpRequestFactory工厂统一设置连接超时时间和读超时时间、代理等信息,然后创建RestTemplate的Bean;
还可以通过SimpleClientHttpRequestFactory工厂配置http请求连接数,忽略ssl证书等;

@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate(ClientHttpRequestFactory simpleClientHttpRequestFactory) {return new RestTemplate(simpleClientHttpRequestFactory);}@Beanpublic ClientHttpRequestFactory simpleClientHttpRequestFactory() {SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();factory.setReadTimeout(10000);//单位为msfactory.setConnectTimeout(10000);//单位为ms//factory.setProxy(null);//设置代理return factory;}
}

请求方式和对应的方法

常规请求调用方法

http method 对应方法
post postForEntity和postForObject
get getForEntity和getForObject
put put
delete delete
Head headForHeaders
options optionsForAllow
options optionsForAllow

通用调用方法

1:exchange:可以自己设置http method、headers、url,传入RequestEntity,返回ResponseEntity
2:execute:通过callback,对请求和返回更好的控制;但是不常用

设置请求参数

JSONObject jsonObject = new JSONObject();
jsonObject.put("payOrderNo", payOrderNo);
jsonObject.put("refundNo", refundNo);
jsonObject.put("refundAmount", refundAmount.multiply(new BigDecimal(100)));
jsonObject.put("refundReason", refundReason);
HttpEntity<JSONObject> httpEntity= new HttpEntity<>(jsonObject);

设置header

 HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add("X-App-Id", appId);
headers.add("X-Time-Stamp", map.get("X-Time-Stamp"));HttpEntity<JSONObject> requestParam = new HttpEntity<>(jsonObject, headers);

请求

//post请求返回ResponseEntityResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);//post请求返回指定的类型
JSONObject responseEntity = restTemplate.postForObject(urls, httpEntity, JSONObject.class);
//get请求返回ResponseEntity
ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(urls, JSONObject.class);//get请求返回指定的类型
JSONObject responseEntity = restTemplate.getForObject(urls, JSONObject.class);

exchange

ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url,HttpMethod.POST,httpEntity, JSONObject.class);

拦截器配置

首先创建拦截器类并实现ClientHttpRequestInterceptor 接口

@Slf4j
public class HTTPInterceptor implements ClientHttpRequestInterceptor {@Overridepublic ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {log.info("执行拦截器拦截请求{}",httpRequest.getURI());return clientHttpRequestExecution.execute(httpRequest,bytes);}
}

在RestTemplate创建bean的时候添加拦截器

    @Beanpublic RestTemplate restTemplate(ClientHttpRequestFactory simpleClientHttpRequestFactory) {RestTemplate restTemplate= new RestTemplate(simpleClientHttpRequestFactory);List<ClientHttpRequestInterceptor> list=new ArrayList<>();list.add(new HTTPInterceptor());restTemplate.setInterceptors(list);return restTemplate;}

这样客户端在发起http请求的时候就会执行拦截器

通过 RestTemplate,我们可以非常方便的进行 Rest API 调用。但是在 Spring 5 中已经不再建议使用 RestTemplate,而是建议使用 WebClient。WebClient 是一个支持异步调用的 Client。

RestTemplat相关推荐

  1. springCloud-4.RestTemplat的使用(两个client之间的调用)

    2019独角兽企业重金招聘Python工程师标准>>> 1.启动eurka-server 2.在client端口8080编写一个hello world方法,并且能访问 3.创建cli ...

  2. RestTemplat发送HTTP请求

    RestTemplate 是一个 spring-web 提供的执行HTTP请求的同步阻塞式工具类. RestTemplate默认是使用SimpleClientHttpRequestFactory,内部 ...

  3. 朱晔和你聊Spring系列S1E7:简单好用的Spring Boot Actuator

    本文会来看一下Spring Boot Actuator提供给我们的监控端点Endpoint.健康检查Health和打点指标Metrics等所谓的Production-ready(生产环境必要的一些)功 ...

  4. 白话SpringCloud | 第五章:服务容错保护(Hystrix)

    前言 前一章节,我们知道了如何利用RestTemplate+Ribbon和Feign的方式进行服务的调用.在微服务架构中,一个服务可能会调用很多的其他微服务应用,虽然做了多集群部署,但可能还会存在诸如 ...

  5. SpringCloud底层原理

    SpringCloud框架 针对这个架构图我分层介绍一下: 1.是web服务器的选型,这个我选择的是nginx+keepalived,haproxy也是一个选择,但是haproxy在反向代理处理跨域访 ...

  6. SpringCloud详细教程(上)

    [订阅专栏合集,关注公众号,作者所有付费文章都能看(持续更新)] 推荐[SpringCloud教程]https://blog.csdn.net/hellozpc/article/details/836 ...

  7. 年轻不学习,老了回村掰苞米!快来学学这份 微服务开发实战派吧

    第一篇 Web基础知识 第1章认识微服务 1.1 什么是微服务框架 1.2 互联网框架的演变 1.3 模块的拆分 文章字数有限制,这里只能展示部分 完整514页PDF文档获取方式:关注+转发后&quo ...

  8. JAVA客户端调用SAP提供的接口(保姆级教程)

    目前接触到SAP提供了两种不同的接口,对应也有两种不同的调用方式:1.Restful接口,支持直接通过post请求调用:2.WSDL接口,需要使用SoapUI测试并生成代码调用.大家在对接前要先确认接 ...

  9. Redis由浅到深层次讲解和springboot实战(服务器层面的搭建部署)

    Redis由深层次讲解到springboot实战 一.Nosql概述 为什么使用Nosql 1.单机Mysql时代 90年代,一个网站的访问量一般不会太大,单个数据库完全够用.随着用户增多,网站出现以 ...

最新文章

  1. LeetCode简单题之找出井字棋的获胜者
  2. APP市场火热的背后 云计算技术不是核心竞争力
  3. java基础系列:集合基础(2)
  4. 六大Web负载均衡原理与实现
  5. Python游戏开发--外星人入侵(源代码)
  6. mac mysql创建本地数据库_【mac】配置本地数据库
  7. JSP 简介(转载)
  8. 84岁院士坚持健身搞科研!病床上辅导多名硕博生完成论文
  9. html页面顶部提示在更高浏览器下面提示语
  10. NFS服务自动搭建及挂载脚本
  11. 无盘服务器pnp,无盘系统PNP方法详细说明
  12. 数十篇推荐系统论文被批无法复现:源码、数据集均缺失!
  13. C#注册类方法到Lua
  14. 浅说position定位及z-index使用
  15. Splash 简介与安装
  16. android 获取刘海高度,不同刘海屏幕获取安全高度
  17. axis webservice 实验
  18. 基于线性回归对男性体脂率的预测
  19. 地毯店人员告诉你如何正确选购合适地毯
  20. SQL注入点判断及万能密码

热门文章

  1. 使用 vs2012 调试驱动
  2. 【ACNET2019】:ATTENTION BASED NETWORK TO EXPLOIT COMPLEMENTARY FEATURES FOR RGBD SEMANTIC SEGMENTATION
  3. 广州达内软件有限公司-3G嵌入式开发助教
  4. 2022年G3锅炉水处理考试试题及模拟考试
  5. 战神 控制中心 controlcenter安装
  6. 电工必备实用口诀 ⑩
  7. 【PMP】第十章、项目沟通管理
  8. Passive device and active device(有源器件和无源器件)
  9. 整个小东西,在IDEA中自动生成PO、DAO、Mapper
  10. 模拟雷神飞机游戏(简易版)