尧图网站建设 尧图网络
  • 首页
  • 关于我们
  • 服务项目
  • 案例展示
  • 建站流程
  • 资讯中心
  • 联系我们
首页/资讯中心/详情

RestTemplate 封装 - RestUtils (1)

RestTemplate 封装 - RestUtils (1)
📅 发布时间:2026/6/20 0:08:37

引入依赖

<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();}}
}

相关新闻

  • H3C MSR3620-DP系列路由器生产环境配置
  • 恶臭异味检测仪:金叶仪器实现异味精准识别与数据化管理
  • 服务器技术参数怎么写

最新新闻

  • 汕头本地人私藏牛肉火锅品牌排行 实地探访口碑解析 - 起跑123
  • 2026年上海名饰回收价格表|真实交易案例+防坑攻略 - 奢侈品交易观察员
  • 2026 上海奢侈品钻石回收权威指南|正规机构筛选公示 - 奢侈品交易观察员
  • 2026年6月最新泰格豪雅中国官方售后电话热线网点地址客服服务 - 亨得利官方服务中心
  • 2026 国内美妆护肤包装设计公司 TOP 榜单|靠谱美妆包装定制机构推荐 - 宏洛图品牌设计
  • Web UI 自动化测试 Skill 完整实战:从一个空项目到一份中文测试报告

日新闻

  • 信任的进化:技术实现详解——如何用JavaScript构建博弈论模拟器
  • Terrakube自定义工作流:如何集成OPA、Infracost等工具扩展IaC能力
  • grunt-concurrent快速入门:5分钟学会并行运行Grunt任务

周新闻

  • 3步解锁iOS设备:applera1n激活锁绕过完全指南
  • 39 2026 人工智能证书终极盘点,普通人选 AI 证书可以从这些方向入手
  • Redis 暴露公网有多危险?从端口检查到补救步骤

月新闻

  • 【总结】入门篇:50句话让你记住架构核心概念
  • WeChatMsg技术方案解析:实现Mac微信数据自主管理的完整解决方案
  • WeChatMsg:革新性微信数据备份方案,打造你的专属数字记忆库

关于尧图

  • 公司简介
  • 团队介绍
  • 企业文化
  • 荣誉资质

服务项目

  • 定制开发
  • 电商建站
  • UI 设计
  • 运维服务

快速链接

  • 案例展示
  • 建站流程
  • 常见问题
  • 资讯中心

联系方式

  • 📍北京市朝阳区互联网产业园 A 座 10 层
  • 📞400-888-8888
  • ✉️contact@rkmt.cn
  • 🕐周一至周日 9:00-21:00

© 2024 北京尧图网络科技有限公司 版权所有 | 京 ICP 备 XXXXXXXX 号