当前位置: 首页 > news >正文

RestTemplate 封装 - RestUtils (1)

引入依赖

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

配置restTemplate

@Bean
public RestTemplate getRestTemplate() {try {// 配置后可以使用 httpsTrustStrategy acceptingTrustStrategy = (x509Certificates, em) -> true;SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();requestFactory.setHttpClient(httpClient);return new RestTemplate(requestFactory);} catch (Exception e) {log.error("getRestTemplate error.", e);}return new RestTemplate();
}

创建工具类

@Component
public class RestUtils {@Autowiredprivate RestTemplate restTemplate;/*** 发送 get 请求*     默认:客户端接受 json 类型数据*/public <T> T get(String url, Class<T> responseType) {// 设置默认请求头Map<String, String> httpHeaderMap = new HashMap<>();httpHeaderMap.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);return sendRequest(url, HttpMethod.GET, null, responseType, httpHeaderMap);}/*** 发送 post 请求*    默认:服务器接受 json 类型数据,客户端接受 json 类型数据*/public <T> T post(String url, Object requestBody, Class<T> responseType) {Map<String, String> httpHeaderMap = new HashMap<>();httpHeaderMap.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);httpHeaderMap.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);return sendRequest(url, HttpMethod.POST, requestBody, responseType, httpHeaderMap);}/*** 发送请求* @param method 请求方式*/public <T> T sendRequest(String url, HttpMethod method, Object requestBody, Class<T> responseType, Map<String, String> httpHeaderMap) {HttpHeaders headers = new HttpHeaders();// 设置请求头httpHeaderMap.keySet().forEach(key -> {headers.add(key,httpHeaderMap.get(key));});HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);return restTemplate.exchange(url, method, entity, responseType).getBody();}/*** 在 url 后面拼接参数* @param url 原请求路径* @param paramMap 参数map*/public String getParamUrl(String url, Map<String, String> paramMap) {StringBuilder sb = new StringBuilder(url);if (paramMap != null && !paramMap.isEmpty()) {sb.append("?");for (Map.Entry<String, String> entry : paramMap.entrySet()) {String key = entry.getKey();String value = entry.getValue();sb.append(key).append("=").append(value).append("&");}sb.deleteCharAt(sb.length() - 1); // 移除最后一个多余的"&"}return sb.toString();}
}

补充:Springboot 3.X,HttpClient 5.0/5.1

<dependency><groupId>org.apache.httpcomponents.client5</groupId><artifactId>httpclient5</artifactId>
</dependency>
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.TrustAllStrategy;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;import javax.net.ssl.SSLContext;
import java.time.Duration;@Slf4j
@Configuration
public class RestConfig {@Beanpublic RestTemplate restTemplate() {try {// 仅测试环境使用:信任所有证书 + 关闭主机名校验SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build();SSLConnectionSocketFactory sslSocketFactory =new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);// 在连接管理器上设置 SSL Socket Factory(适用于 HttpClient 5.0/5.1)PoolingHttpClientConnectionManager cm =PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).build();CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);requestFactory.setConnectTimeout(Duration.ofSeconds(10));requestFactory.setConnectionRequestTimeout(Duration.ofSeconds(10));requestFactory.setReadTimeout(Duration.ofSeconds(30));return new RestTemplate(requestFactory);} catch (Exception e) {log.error("Create RestTemplate error.", e);return new RestTemplate();}}
}
http://www.jsqmd.com/news/111007/

相关文章:

  • 天地图Python SDK终极指南:如何快速掌握地图切片下载与数据处理
  • 如何彻底解决Android截屏限制?Enable Screenshot终极解决方案指南
  • macOS存储空间不足?3步解锁远程存储新方案
  • macOS存储扩展深度解析:iSCSI远程存储技术实战指南
  • 2025无锡GEO优化指南:AI驱动的精准获客服务商优选 - 品牌推荐排行榜
  • Python背景移除终极指南:remove-bg完整使用教程
  • H3C MSR3620-DP系列路由器生产环境配置
  • 大语言模型~Ollama本地模型和java一起体验LLM
  • 恶臭异味检测仪:金叶仪器实现异味精准识别与数据化管理
  • 服务器技术参数怎么写
  • web渗透测试之CSRF实战案例,告知你如何玩转CSRF跨站脚本伪造攻击、短链接、以及结合XSS漏洞组合
  • 卷不动样本量?来抄作业:细菌基因组如何发顶刊?
  • 别花钱找中介,我留学生求职却靠它上岸了!
  • 关键操作:锁相环切换、逆变器控制模式切换
  • 一篇文章了解深拷贝和浅拷贝
  • ESP32音频革命:P3专有格式的终极指南与实战技巧
  • 前后端分离短流量数据分析与可视化abo系统|SpringBoot+Vue+MyBatis+MySQL完整源码+部署教程
  • 小团队如何1-2周快速搭建企业级外卖平台?
  • 对我来讲不太常用却很有用的linux命令
  • 计算机毕业设计springboot皮影文化科普平台的设计与实现 基于SpringBoot的非遗皮影数字传播平台构建 面向Web的皮影艺术互动展示与科普系统研发
  • TikTok电商深度跃迁:谁能从“广撒网”玩家,变身区域经营专家?
  • AI人工智能小动物精细行为 AI人工智能精细行为分析系统 多功能整合型精细行为识别分析系统 AI人工智能大小鼠精细行为分析系统
  • 扩展温度缩放技术:同质化映射提升模型校准
  • 如何快速实现多平台自动签到:qd-templates完整使用指南
  • WEB前端都是先混进去再说,过来人的经验
  • Dbca slient create database ORA-15001: diskgroup “DATA does not exist or is not mounted
  • Win-PS2EXE:PowerShell脚本编译为EXE的终极解决方案
  • 100+网站自动签到终极指南:qd-templates Har模板库完整教程
  • FPGA技术:HDMI至SDI视频输出转换的完整解决方案,附赠四套工程源码及详细设计文档参考
  • 快速掌握图表定制:新手友好的交互式数据可视化终极指南