springboot配置并使用RestTemplate

目录

一、RestTemplate配置

1、将RestTemplate初始化为Bean

2、使用HttpClient作为RestTemplate客户端

(1)引入HttpClient依赖

(2)修改RestTemplate配置类

3、设置拦截器

(1)新增拦截器类

(2)设置拦截器

4、新增支持的媒体类型

二、RestTemplate使用

1、RestTemplate注入

2、无参数get请求测试

(1)Controller代码

(2)RestTemplate单元测试

3、带参get请求测试

(1)Controller代码

(2)RestTemplate单元测试

4、带占位符参数的get请求测试

(1)Controller代码

(2)RestTemplate单元测试

5、post请求测试

(1)Article实体类

(2)Controller代码

(3)RestTemplate单元测试

6、设置请求头

(1)Article实体类

(2)Controller代码

(3)RestTemplate单元测试

7、上传文件

(1)Controller代码

(2)RestTemplate单元测试

8、文件下载

(1)Controller代码

(2)RestTemplate单元测试

三、参考


一、RestTemplate配置

1、将RestTemplate初始化为Bean

package com.xiaobai.conf;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;import java.util.Collections;/*** @Author 王天文* @Date 2024/12/29 18:06* @Description: RestTemplate配置类*/
@Configuration
public class RestTemplateConf {/*** 当指定类型Bean不存在时,会创建一个新的Bean,如果用户自定义了Bean,将使用用户自定义的Bean* @return*/@ConditionalOnMissingBean(RestTemplate.class)@Beanpublic RestTemplate restTemplate() {// 使用JDK自带的HttpURLConnection作为客户端RestTemplate restTemplate = new RestTemplate();return restTemplate;}
}

2、使用HttpClient作为RestTemplate客户端

(1)引入HttpClient依赖

        <!--httpclient--><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.7</version></dependency>

(2)修改RestTemplate配置类

package com.xiaobai.conf;import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;import java.util.Collections;/*** @Author 王天文* @Date 2024/12/29 18:06* @Description: RestTemplate配置类*/
@Configuration
public class RestTemplateConf {/*** 当指定类型Bean不存在时,会创建一个新的Bean,如果用户自定义了Bean,将使用用户自定义的Bean* @return*/@ConditionalOnMissingBean(RestTemplate.class)@Beanpublic RestTemplate restTemplate() {// 使用httpclient作为底层客户端RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());return restTemplate;}/*** 使用httpclient作为底层客户端* @return*/@Beanpublic ClientHttpRequestFactory getClientHttpRequestFactory() {int timeout = 50000;RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();return new HttpComponentsClientHttpRequestFactory(httpClient);}
}

3、设置拦截器

(1)新增拦截器类

package com.xiaobai.conf;import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;import java.io.IOException;/*** @Author 王天文* @Date 2024/12/22 21:51* @Description: restTemplate拦截器*/
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {@Overridepublic ClientHttpResponse intercept(HttpRequest httpRequest,byte[] bytes,ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {ClientHttpResponse httpResponse = clientHttpRequestExecution.execute(httpRequest, bytes);return httpResponse;}
}

(2)设置拦截器

package com.xiaobai.conf;import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;import java.util.Collections;/*** @Author 王天文* @Date 2024/12/29 18:06* @Description: RestTemplate配置类*/
@Configuration
public class RestTemplateConf {/*** 当指定类型Bean不存在时,会创建一个新的Bean,如果用户自定义了Bean,将使用用户自定义的Bean* @return*/@ConditionalOnMissingBean(RestTemplate.class)@Beanpublic RestTemplate restTemplate() {// 使用JDK自带的HttpURLConnection作为客户端RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());// 设置拦截器restTemplate.setInterceptors(Collections.singletonList(restTemplateInterceptor()));return restTemplate;}/*** 使用httpclient作为底层客户端* @return*/@Beanpublic ClientHttpRequestFactory getClientHttpRequestFactory() {int timeout = 50000;RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();return new HttpComponentsClientHttpRequestFactory(httpClient);}/*** 拦截器* @return*/@Beanpublic RestTemplateInterceptor restTemplateInterceptor() {return new RestTemplateInterceptor();}
}

4、新增支持的媒体类型

RestTemplate 只支持application/json格式,需要手动补充text/plan,text/html格式

package com.xiaobai.conf;import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;import java.util.Arrays;
import java.util.Collections;/*** @Author 王天文* @Date 2024/12/29 18:06* @Description: RestTemplate配置类*/
@Configuration
public class RestTemplateConf {/*** 当指定类型Bean不存在时,会创建一个新的Bean,如果用户自定义了Bean,将使用用户自定义的Bean* @return*/@ConditionalOnMissingBean(RestTemplate.class)@Beanpublic RestTemplate restTemplate() {// 使用JDK自带的HttpURLConnection作为客户端RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());// 设置拦截器restTemplate.setInterceptors(Collections.singletonList(restTemplateInterceptor()));// 增加支持的媒体类型restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter());return restTemplate;}/*** 使用httpclient作为底层客户端* @return*/@Beanpublic ClientHttpRequestFactory getClientHttpRequestFactory() {int timeout = 50000;RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();return new HttpComponentsClientHttpRequestFactory(httpClient);}/*** 拦截器* @return*/@Beanpublic RestTemplateInterceptor restTemplateInterceptor() {return new RestTemplateInterceptor();}/*** 媒体类型* @return*/@Beanpublic MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {// RestTemplate 只支持application/json格式,需要手动补充text/html格式MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.TEXT_HTML));return mappingJackson2HttpMessageConverter;}
}

二、RestTemplate使用

1、RestTemplate注入

    @Autowiredprivate RestTemplate restTemplate;

2、无参数get请求测试

(1)Controller代码

    @GetMapping(value = "/getString")public String getString() {return "操作成功";}

(2)RestTemplate单元测试

    @Testpublic void testGetString() {ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8090/getString", String.class);log.info(responseEntity.getBody());}

3、带参get请求测试

(1)Controller代码

    @GetMapping("/getRequestByParam")public Map<String, Object> getRequestByParam(@RequestParam("name") String name) {log.info("名称:" + name);Map<String, Object> map = new HashMap<>();map.put("responseData", "请求成功");return map;}

(2)RestTemplate单元测试

    @Testpublic void testParamGet() throws Exception {Map<String, Object> param = new HashMap<>();param.put("name", "张三");ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8090/getRequestByParam?name={name}", String.class, param);log.info("响应信息:{}", responseEntity.getBody());}

4、带占位符参数的get请求测试

(1)Controller代码

    @GetMapping("/getRequestByPlaceHolder/{name}/{age}")public Map<String, Object> getRequestByPlaceHolder(@PathVariable("name") String name,@PathVariable("age") String age) {log.info("名称:" + name);log.info("年龄:" + age);Map<String, Object> map = new HashMap<>();map.put("responseData", "请求成功");return map;}

(2)RestTemplate单元测试

    @Testpublic void testPlaceholderGet() {ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8090/getRequestByPlaceHolder/{1}/{2}", String.class, "张三", "25");log.info("响应信息:{}", responseEntity.getBody());}

5、post请求测试

(1)Article实体类

package com.xiaobai.aroundtest.entity;import lombok.Data;import java.io.Serializable;/*** @author wangtw* @date 2023/12/6 0:35* @description*/
@Data
public class Article implements Serializable {private static final long serialVersionUID = 1L;/*** 文章名称*/private String name;/*** 描述*/private String description;
}

(2)Controller代码

    @PostMapping("/postRequest")public Map<String, Object> postRequest(@RequestParam String name, @RequestBody Article article) {log.info("名称:" + name);log.info("文章名称:" + article.getName());log.info("文章描述:" + article.getDescription());Map<String, Object> map = new HashMap<>();map.put("responseData", "请求成功");return map;}

(3)RestTemplate单元测试

    @Testpublic void testPost() {// 表单数据Map<String, Object> formData = new HashMap<>();formData.put("name", "解忧杂货店");formData.put("description", "这是一本好书");// 单独传参Map<String, Object> param = new HashMap<>();param.put("name", "东野圭吾");// 请求调用HttpEntity<Map<String, Object>> formEntity = new HttpEntity<>(formData);ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8090/postRequest?name={name}", formEntity, String.class, param);log.info("响应信息:{}", responseEntity.getBody());}

6、设置请求头

(1)Article实体类

package com.xiaobai.aroundtest.entity;import lombok.Data;import java.io.Serializable;/*** @author wangtw* @date 2023/12/6 0:35* @description*/
@Data
public class Article implements Serializable {private static final long serialVersionUID = 1L;/*** 文章名称*/private String name;/*** 描述*/private String description;
}

(2)Controller代码

    @PostMapping("/postRequestHeader")public Map<String, Object> postRequestHeader(HttpServletRequest request,@RequestParam String name, @RequestBody Article article) {String token = request.getHeader("token");log.info("请求token:" + token);log.info("名称:" + name);log.info("文章名称:" + article.getName());log.info("文章描述:" + article.getDescription());Map<String, Object> map = new HashMap<>();map.put("responseData", "请求成功");return map;}

(3)RestTemplate单元测试

    @Testpublic void testPostHeader() {// 请求头HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.add("token", "123456");// 表单数据Map<String, Object> formData = new HashMap<>();formData.put("name", "解忧杂货店");formData.put("description", "这是一本好书");// 单独传参Map<String, Object> param = new HashMap<>();param.put("name", "东野圭吾");// 请求调用HttpEntity<Map<String, Object>> formEntity = new HttpEntity<>(formData, httpHeaders);ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8090/postRequestHeader?name={name}", formEntity, String.class, param);log.info("响应信息:{}", responseEntity.getBody());}

7、上传文件

(1)Controller代码

    @PostMapping("/upload")public Map<String, Object> upload(@RequestParam String name, MultipartFile uploadFile) throws IOException {log.info("名称:" + name);uploadFile.transferTo(new File("D:\\temp/" + uploadFile.getOriginalFilename()));Map<String, Object> map = new HashMap<>();map.put("responseData", "请求成功");return map;}

(2)RestTemplate单元测试

    @Testpublic void testUploadFile() {MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();param.add("uploadFile", new FileSystemResource(new File("D:\\christmas-tree.svg")));param.add("name", "张三");// 请求头设置HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.MULTIPART_FORM_DATA);// 请求调用HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(param, headers);ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8090/upload", formEntity, String.class);log.info("响应信息:{}", responseEntity.getBody());}

8、文件下载

(1)Controller代码

    @PostMapping("/download")public Map<String, Object> download(@RequestParam String fileName,HttpServletResponse response) {log.info("文件名称:" + fileName);File file = new File("D:\\temp/" + fileName);try(FileInputStream fileInputStream = new FileInputStream(file);ServletOutputStream outputStream = response.getOutputStream()) {response.setHeader("content-disposition","attachment;fileName=" + URLEncoder.encode(fileName,"UTF-8"));FileCopyUtils.copy(fileInputStream, outputStream);} catch (Exception e) {e.printStackTrace();}Map<String, Object> map = new HashMap<>();map.put("responseData", "请求成功");return map;}

(2)RestTemplate单元测试

    @Testpublic void testDownloadFile() {MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();param.add("fileName", "christmas-tree.svg");// 请求调用HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(param);ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity("http://localhost:8090/download", formEntity, byte[].class);// 获取响应头HttpHeaders responseEntityHeaders = responseEntity.getHeaders();Set<Map.Entry<String, List<String>>> responseSet = responseEntityHeaders.entrySet();for (Map.Entry<String, List<String>> responseValue : responseSet) {log.info("响应头:" + responseValue.getKey() + ",响应内容:" + responseValue.getValue());}try {// 文件保存byte[] fileData = responseEntity.getBody();FileCopyUtils.copy(fileData, new File("D:\\christmas-tree1.svg"));} catch (IOException e) {e.printStackTrace();}}

三、参考

Spring之RestTemplate详解

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

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

相关文章

【数据仓库】SparkSQL数仓实践

文章目录 集成hive metastoreSQL测试spark-sql 语法SQL执行流程两种数仓架构的选择hive on spark数仓配置经验 spark-sql没有元数据管理功能&#xff0c;只有sql 到RDD的解释翻译功能&#xff0c;所以需要和hive的metastore服务集成在一起使用。 集成hive metastore 在spark安…

基本算法——回归

本节将通过分析能源效率数据集&#xff08;Tsanas和Xifara&#xff0c;2012&#xff09;学习基本的回归算法。我们将基 于建筑的结构特点&#xff08;比如表面、墙体与屋顶面积、高度、紧凑度&#xff09;研究它们的加热与冷却负载要 求。研究者使用一个模拟器设计了12种不…

V-Express - 一款针对人像视频生成的开源软件

V-Express是腾讯AI Lab开发的一款针对人像视频生成的开源软件。它旨在通过条件性丢弃&#xff08;Conditional Dropout&#xff09;技术&#xff0c;实现渐进式训练&#xff0c;以改善使用单一图像生成人像视频时的控制信号平衡问题。 在生成过程中&#xff0c;不同的控制信号&…

Java与SQL Server数据库连接的实践与要点

本文还有配套的精品资源&#xff0c;点击获取 简介&#xff1a;Java和SQL Server数据库交互是企业级应用开发中的重要环节。本文详细探讨了使用Java通过JDBC连接到SQL Server数据库的过程&#xff0c;包括加载驱动、建立连接、执行SQL语句、处理异常、资源管理、事务处理和连…

学习记录—正则表达式-基本语法

正则表达式简介-《菜鸟教程》 正则表达式是一种用于匹配和操作文本的强大工具&#xff0c;它是由一系列字符和特殊字符组成的模式&#xff0c;用于描述要匹配的文本模式。 正则表达式可以在文本中查找、替换、提取和验证特定的模式。 本期内容将介绍普通字符&#xff0c;特殊…

企业安装加密软件有什么好处?

加密软件为企业的安全提供了很多便利&#xff0c;从以下几点我们看看比较重要的几个优点&#xff1a; 1、数据保护&#xff1a;企业通常拥有大量的商业机密、客户数据、技术文档等敏感信息。加密软件可以对这些信息进行加密处理&#xff0c;防止未经授权的人员访问。即使数据被…

音视频学习(二十八):websocket-flv

FLV视频流格式 FLV (Flash Video) 是一种轻量化的视频封装格式&#xff0c;适合实时流媒体传输&#xff0c;主要特点包括&#xff1a; 轻量级封装&#xff1a;封装开销低&#xff0c;适合在网络上传输。流式播放&#xff1a;支持边下载边播放&#xff0c;特别适合直播场景。适…

AduSkin、WPF-UI、Prism:WPF 框架全解析与应用指南

摘要: 本文深入探讨了 AduSkin、WPF-UI、Prism 这三个在 WPF 开发领域极具影响力的框架。详细阐述了每个框架的特点、核心功能、安装与配置过程,并通过丰富的代码示例展示其在实际应用场景中的使用方式,包括界面美化、导航与模块管理等方面。同时对它们的优势与局限性进行了…

京东供应链创新与实践:应用数据驱动的库存选品和调拨算法提升履约效率

2024 年度总结系列 2024 年 10 月&#xff0c;京东零售供应链技术团队凭借其在库存选品与调拨技术上的创新与实践&#xff0c;荣获运筹与管理学领域的国际顶级奖项 Daniel H. Wagner Prize。本文为您介绍获奖背后的供应链技术创新和落地应用。 00 摘要 在电商行业中&#x…

大数据技术-Hadoop(二)HDFS的介绍与使用

目录 1、HDFS简介 1.1 什么是HDFS 1.2 HDFS的优点 1.3、HDFS的架构 1.3.1、 NameNode 1.3.2、 NameNode的职责 1.3.3、DataNode 1.3.4、 DataNode的职责 1.3.5、Secondary NameNode 1.3.6、Secondary NameNode的职责 2、HDFS的工作原理 2.1、文件存储 2.2 、数据写…

数据科学团队管理

定位&#xff1a; 有核心竞争力的工业算法部门与PM、RD等深度合作 业务方向&#xff1a;(不同产品线&#xff09; 工业预测性维护与数据挖掘视觉检测、OCR 工作内容 项目需求与交付内部框架(frameworks \packages)应用demo专利、竞赛、论文 日常管理 项目管理数据管理(原…

如何保证mysql数据库到ES的数据一致性

1.同步双写方案 在代码中对数据库和ES进行双写操作&#xff0c;确保先更新数据后更新ES。 优点&#xff1a; 数据一致性&#xff1a;双写策略可以保证在MySql和Elasticsearch之间数据的强一致性&#xff0c;因为每次数据库的变更都会在Elasticsearch同步反映。实时性&#xf…

敏捷测试文化的转变

敏捷文化是敏捷测试转型的基础&#xff0c;只有具备敏捷文化的氛围&#xff0c;对组织架构、流程和相关测试实践的调整才能起作用。在前面的敏捷测试定义中&#xff0c;敏捷测试是遵从敏捷软件开发原则的一种测试实践&#xff0c;这意味着敏捷的价值观。 此外&#xff0c;从传…

在 C# 中优化 JPEG 压缩级别和文件大小

此示例可让您检查不同 JPEG 压缩级别的图像质量。使用文件菜单的打开命令加载图像文件。然后使用“JPEG 压缩指数 (CI)”组合框选择压缩级别。程序将图像保存到具有该压缩级别的临时文件中&#xff0c;并显示生成的图像和文件大小。 该程序的关键是以下SaveJpg方法&#xff0c;…

Pandas02

Pandas01: Pandas01 文章目录 内容回顾1 数据的读取和保存1.1 读写Excel文件1.2 读写CSV1.3 读写Mysql 2 DataFrame 数据查询2.1 筛选多列数据2.2 loc 和 iloc2.3 query查询方法和isin 方法 3 DataFrame增 删 改数据3.1 增加一列数据3.2 删除一行/一列数据3.3 数据去重3.4 数据…

Flink定时器

flink的定时器都是基于事件时间&#xff08;event time&#xff09;或事件处理时间&#xff08;processing time&#xff09;的变化来触发响应的。对一部分新手玩家来说&#xff0c;可能不清楚事件时间和事件处理时间的区别。我这里先说一下我的理解&#xff0c;防止下面懵逼。…

Docker中的分层(Layer)

docker中有分层的概念&#xff0c;如下图所示 上面是容器层&#xff08;Container layer&#xff09;&#xff0c;下面是镜像层&#xff08;Image layers&#xff09;。 镜像层的内容是静态的&#xff0c;读和写的操作&#xff0c;都是在容器层发生&#xff0c;专门为容器的读…

RoboMIND:多体现基准 机器人操纵的智能规范数据

我们介绍了 RoboMIND&#xff0c;这是机器人操纵的多体现智能规范数据的基准&#xff0c;包括 4 个实施例、279 个不同任务和 61 个不同对象类别的 55k 真实世界演示轨迹。 工业机器人企业 埃斯顿自动化 | 埃夫特机器人 | 节卡机器人 | 珞石机器人 | 法奥机器人 | 非夕科技 | C…

用友-友数聚科技CPAS审计管理系统V4 getCurserIfAllowLogin存在SQL注入漏洞

免责声明: 本文旨在提供有关特定漏洞的深入信息,帮助用户充分了解潜在的安全风险。发布此信息的目的在于提升网络安全意识和推动技术进步,未经授权访问系统、网络或应用程序,可能会导致法律责任或严重后果。因此,作者不对读者基于本文内容所采取的任何行为承担责任。读者在…

python报错ModuleNotFoundError: No module named ‘visdom‘

在用虚拟环境跑深度学习代码时&#xff0c;新建的环境一般会缺少一些库&#xff0c;而一般解决的方法就是直接conda install&#xff0c;但是我在conda install visdom之后&#xff0c;安装是没有任何报错的&#xff0c;conda list里面也有visdom的信息&#xff0c;但是再运行代…