spring框架自带的http工具RestTemplate用法

1. RestTemplate是什么?

RestTemplate是由Spring框架提供的一个可用于应用中调用rest服务的类它简化了与http服务的通信方式。
RestTemplate是一个执行HTTP请求的同步阻塞式工具类,它仅仅只是在 HTTP 客户端库(例如 JDK HttpURLConnection,Apache HttpComponents,okHttp 等)基础上,封装了更加简单易用的模板方法 API,方便程序员利用已提供的模板方法发起网络请求和处理,能很大程度上提升我们的开发效率。

2. HttpClient、OKhttp、RestTemplate对比

HttpClient:代码复杂,还得操心资源回收等。代码很复杂,冗余代码多,不建议直接使用。

创建HttpClient对象。
创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
如果需要发送请求参数,可调用HttpGetHttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
调用HttpResponsegetAllHeaders()getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponsegetEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
释放连接。无论执行方法是否成功,都必须释放连接。

okhttp:OkHttp是一个高效的HTTP客户端,允许所有同一个主机地址的请求共享同一个socket连接;连接池减少请求延时;透明的GZIP压缩减少响应数据的大小;缓存响应内容,避免一些完全重复的请求。

RestTemplate: 是 Spring 提供的用于访问Rest服务的客户端, RestTemplate 提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。

3. 使用RestTemplate

pom

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

初始化

RestTemplate restTemplate = new RestTemplate(); //使用了JDK自带的HttpURLConnection
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
//集成 HttpClient客户端
RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
//集成 okhttp

常用接口和参数:
getForObject:返回值直接是响应体内容转为的 JSON 对象
getForEntity:返回值的封装包含有响应头, 响应状态码的 ResponseEntity对象
url:请求路径
requestEntity:HttpEntity对象,封装了请求头和请求体
responseType:返回数据类型
uriVariables:支持PathVariable类型的数据。

4. Get

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> entity = restTemplate.getForEntity(uri, String.class);
// TODO 处理响应
@Test
public void test1() {RestTemplate restTemplate = new RestTemplate();String url = "http://localhost:8080/chat16/test/get";//getForObject方法,获取响应体,将其转换为第二个参数指定的类型BookDto bookDto = restTemplate.getForObject(url, BookDto.class);System.out.println(bookDto);
}@Test
public void test2() {RestTemplate restTemplate = new RestTemplate();String url = "http://localhost:8080/chat16/test/get";//getForEntity方法,返回值为ResponseEntity类型// ResponseEntity中包含了响应结果中的所有信息,比如头、状态、bodyResponseEntity<BookDto> responseEntity = restTemplate.getForEntity(url, BookDto.class);//状态码System.out.println(responseEntity.getStatusCode());//获取头System.out.println("头:" + responseEntity.getHeaders());//获取bodyBookDto bookDto = responseEntity.getBody();System.out.println(bookDto);
}
@Test
public void test3() {RestTemplate restTemplate = new RestTemplate();//url中有动态参数String url = "http://localhost:8080/chat16/test/get/{id}/{name}";Map<String, String> uriVariables = new HashMap<>();uriVariables.put("id", "1");uriVariables.put("name", "SpringMVC系列");//使用getForObject或者getForEntity方法BookDto bookDto = restTemplate.getForObject(url, BookDto.class, uriVariables);System.out.println(bookDto);
}@Test
public void test4() {RestTemplate restTemplate = new RestTemplate();//url中有动态参数String url = "http://localhost:8080/chat16/test/get/{id}/{name}";Map<String, String> uriVariables = new HashMap<>();uriVariables.put("id", "1");uriVariables.put("name", "SpringMVC系列");//getForEntity方法ResponseEntity<BookDto> responseEntity = restTemplate.getForEntity(url, BookDto.class, uriVariables);BookDto bookDto = responseEntity.getBody();System.out.println(bookDto);
}

5. Post

RestTemplate restTemplate = new RestTemplate();
// headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<Object> objectHttpEntity = new HttpEntity<>(headers);ResponseEntity<String> entity = restTemplate.postForEntity(uri, request, String.class);
// TODO 处理响应
    public static void main(String[] args) {RestTemplate restTemplate = new RestTemplate();//三种方式请求String url = "https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=3ff9482454cb60bcb73f65c8c48d4209](https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=3ff9482454cb60bcb73f65c8c48d4209)";Map<String,Object> params=new HashMap<>();ResponseEntity<String> result = restTemplate.postForEntity(url,params, String.class);System.out.println(result.getStatusCode().getReasonPhrase());System.out.println(result.getStatusCodeValue());System.out.println(result.getBody());}
@Autowired
private RestTemplate restTemplate;/*** 模拟表单提交,post请求*/
@Test
public void testPostByForm(){//请求地址String url = "http://localhost:8080/testPostByForm";// 请求头设置,x-www-form-urlencoded格式的数据HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);//提交参数设置MultiValueMap<String, String> map = new LinkedMultiValueMap<>();map.add("userName", "唐三藏");map.add("userPwd", "123456");// 组装请求体HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);//发起请求ResponseBean responseBean = restTemplate.postForObject(url, request, ResponseBean.class);System.out.println(responseBean.toString());
}

6. Put

@Autowired
private RestTemplate restTemplate;
/*** 模拟JSON提交,put请求*/
@Test
public void testPutByJson(){//请求地址String url = "http://localhost:8080/testPutByJson";//入参RequestBean request = new RequestBean();request.setUserName("唐三藏");request.setUserPwd("123456789");//模拟JSON提交,put请求restTemplate.put(url, request);
}

7. Delete

@Autowired
private RestTemplate restTemplate;
/*** 模拟JSON提交,delete请求*/
@Test
public void testDeleteByJson(){//请求地址String url = "http://localhost:8080/testDeleteByJson";//模拟JSON提交,delete请求restTemplate.delete(url);
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/29788.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python 相关框架事务开启方式

前言 对于框架而言&#xff0c;各式API接口少不了伴随着事务的场景&#xff0c;下面就列举常用框架的事务开启方法 一、Django import traceback from django.db import transaction from django.contrib.auth.models import User try:with transaction.atomic(): # 在with…

利用appium抓取app中的信息

一、appium简介 二、appium环境安装 三、联调测试环境 四、利用appium自动控制移动设备并提取数据

nginx location的执行规则和root/alias的区分

nginx location的执行规则和root/alias的区分 总结 看本篇文章不是教如何从0编写nginx配置&#xff0c;而是看懂已存在的nginx配置。 官方文档定义&#xff1a;location [ | ~ | ~* | ^~ ] uri { … } &#xff1a;严格匹配&#xff0c;且匹配成功则不继续往下&#xff0c;优…

【openGauss】分区表的介绍与使用

一、openGauss分区表介绍 在openGauss中&#xff0c;数据分区是在一个节点内部对数据按照用户指定的策略做进一步的水平分表&#xff0c;将表中的数据按照指定方式划分为多个互不重叠的部分。 对于大多数用户使用场景&#xff0c;分区表和普通表相比具有以下优点&#xff1a; …

年轻代频繁GC ParNew导致http变慢

背景介绍 某日下午大约四点多&#xff0c;接到合作方消息&#xff0c;线上环境&#xff0c;我这边维护的某http服务突然大量超时&#xff08;对方超时时间设置为300ms&#xff09;&#xff0c;我迅速到鹰眼平台开启采样&#xff0c;发现该服务平均QPS到了120左右&#xff0c;平…

希尔排序——C语言andPython

前言 步骤 代码 C语言 Python 总结 前言 希尔排序&#xff08;Shell Sort&#xff09;是一种改进的插入排序算法&#xff0c;它通过将数组分成多个子序列进行排序&#xff0c;逐步减小子序列的长度&#xff0c;最终完成整个数组的排序。希尔排序的核心思想是通过排序较远距…

SQL server 异地备份数据库

异地备份数据库 1.备份服务器中设置共享文件夹 2.源服务器数据库中添加异地备份代理作业 EXEC sp_configure show advanced options, 1;RECONFIGURE; EXEC sp_configure xp_cmdshell, 1;RECONFIGURE; declare machine nvarchar(50) 192.168.11.10 --服务器IP declare pa…

中科驭数亮相DPU峰会,分享HADOS软件生态实践和大数据计算方案,再获评“匠芯技术奖”

又是一年相逢时&#xff0c;8月4日&#xff0c;第三届DPU峰会在北京开幕&#xff0c;本届峰会由中国通信学会指导&#xff0c;江苏省未来网络创新研究院主办&#xff0c;SDNLAB社区承办&#xff0c;以“智驱创新芯动未来”为主题&#xff0c;沿袭技术创新、生态协同的共创效应&…

Vue-1.零基础学习Vue

当你从零开始学习 Vue.js 时&#xff0c;以下步骤可以帮助你系统地学习这个前端框架&#xff1a; 了解前端基础&#xff1a; 如果你对前端开发还不熟悉&#xff0c;可以先了解 HTML、CSS 和 JavaScript 的基础知识。这将为学习 Vue.js 奠定基础。 Vue.js 官方文档&#xff1…

【打印整数二进制的奇数位和偶数位】

打印整数二进制的奇数位和偶数位 1.题目 获取一个整数二进制序列中所有的偶数位和奇数位&#xff0c;分别打印出二进制序列 2.题目分析 打印一个整数的二进制位中的偶数位和奇数位&#xff0c;可以对整数进行移位操作&#xff0c;再将移位的二进制位与1进行&操作。 按位&a…

word将mathtype公式批量转为latex公式

最近&#xff0c;由于工作学习需要&#xff0c;要将word里面的mathype公式转为latex公式。 查了查资料&#xff0c;有alt\的操作&#xff0c;这样太慢了。通过下面链接的操作&#xff0c;结合起来可以解决问题。 某乎&#xff1a;https://www.zhihu.com/question/532353646 csd…

基于BNC和RTKLIB的GNSS组件包-星历设计

星历模块 主要包括如下&#xff1a;星历本身的数据结构&#xff0c;星历的编码解码和 rinex格式的文件读写等功能 星历分析工具主要包括&#xff1a;对应卫星更新 每个卫星星历的健康标记序列&#xff0c;星历的位置序列图 各个模块的组件图&#xff1a; class Eph { public:…

datePicker一个或多个日期组件,如何快捷选择多个日期(时间段)

elementUI的组件文档中没有详细说明type"dates"如何快捷选择一个时间段的日期&#xff0c;我们可以通过picker-options参数来设置快捷选择&#xff1a; <div class"block"><span class"demonstration">多个日期</span><el…

【Azure】office365邮箱测试的邮箱账号因频繁连接邮箱服务器而被限制连接 引起邮箱显示异常

azure微软office365邮箱会对频繁连接自身邮箱服务器的IP地址进行&#xff0c;连接邮箱服务器IP限制&#xff0c;也就是黑名单&#xff0c;释放时间不确定&#xff0c;但至少一天及以上。 解决办法&#xff0c;换一个IP&#xff0c;或者新注册一个office365邮箱再重试。 以下是…

Java课题笔记~ AspectJ 对 AOP 的实现(掌握)

AspectJ 对 AOP 的实现(掌握) 对于 AOP 这种编程思想&#xff0c;很多框架都进行了实现。Spring 就是其中之一&#xff0c;可以完成面向切面编程。然而&#xff0c;AspectJ 也实现了 AOP 的功能&#xff0c;且其实现方式更为简捷&#xff0c;使用更为方便&#xff0c;而且还支…

JVM 类加载和垃圾回收

JVM 1. 类加载1.1 类加载过程1.2 双亲委派模型 2. 垃圾回收机制2.1 死亡对象的判断算法2.2 垃圾回收算法 1. 类加载 1.1 类加载过程 对应一个类来说, 它的生命周期是这样的: 其中前 5 步是固定的顺序并且也是类加载的过程&#xff0c;其中中间的 3 步我们都属于连接&#xf…

用node.js搭建一个视频推流服务

由于业务中有不少视频使用的场景&#xff0c;今天来说说如何使用node完成一个视频推流服务。 先看看效果&#xff1a; 这里的播放的视频是一个多个Partial Content组合起来的&#xff0c;每个Partial Content大小是1M。 一&#xff0c;项目搭建 &#xff08;1&#xff09;初…

React Native Camera的使用

介绍 React Native Camera是一个用于在React Native应用中实现相机功能的库。它允许你访问设备的摄像头&#xff0c;并捕获照片和视频。 使用 安装 npm install react-native-camera --save 安装完成后&#xff0c;你需要链接React Native Camera库到你的项目中。可以使用以…

macOS下Django环境搭建-docker运行Django

1. macOS升级pip /Library/Developer/CommandLineTools/usr/bin/python3 -m pip install --upgrade pip 2. 卸载Python3.9.5版本 $ sudo rm -rf /usr/local/bin/python3 $ sudo rm -rf /usr/local/bin/pip3 $ sudo rm -rf /Library/Frameworks/Python.framework 3. 安装P…

微服务——ES实现自动补全

效果展示 在搜索框根据拼音首字母进行提示 拼音分词器 和IK中文分词器一样的用法&#xff0c;按照下面的顺序执行。 # 进入容器内部 docker exec -it elasticsearch /bin/bash# 在线下载并安装 ./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch…