Springboot 使用restTemplate发送https请求忽略ssl证书完整方案

Springboot版本:6.x, HttpClient版本:5.x

需求:除了要忽略SSL证书,还要在请求头里加参数。

xml 复制代码
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
</dependency>
java 复制代码
import org.apache.hc.client5.http.classic.HttpClient;
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.core5.http.HttpRequestInterceptor;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.apache.hc.core5.ssl.TrustStrategy;

public class SSLIgnoreConfig{

    /**
     * 创建忽略证书的请求工厂
     */
    public static ClientHttpRequestFactory insecureRequestFactory() 
            throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        
        // 信任所有证书的策略
        TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;
        
        // 创建 SSLContext
        SSLContext sslContext = SSLContextBuilder.create()
                .loadTrustMaterial(acceptingTrustStrategy)
                .build();
        
        // 创建 SSL 连接套接字工厂
        SSLConnectionSocketFactory sslSocketFactory = 
                new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        
        // 创建连接管理器
        PoolingHttpClientConnectionManager connectionManager = 
                PoolingHttpClientConnectionManagerBuilder.create()
                        .setSSLSocketFactory(sslSocketFactory)
                        .build();
        
        HttpRequestInterceptor httpRequestInterceptor = (request, entity, context) -> {
        // 关键:在 HttpClient 层面添加额外的头信息
        request.setHeader("key", "47953053953");
        request.setHeader("secret", "dsbkflsehgwlledksv");
    };
        
        // 创建 HttpClient
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setConnectionManagerShared(true)  // 共享连接管理器
                .evictExpiredConnections()  // 清理过期连接
                .evictIdleConnections(Duration.ofSeconds(30))  // 清理空闲连接
                .build();
        
        // 创建 RequestFactory
        HttpComponentsClientHttpRequestFactory requestFactory = 
                new HttpComponentsClientHttpRequestFactory(httpClient);
        
        
        return requestFactory;
    }
}
less 复制代码
@Configuration
public class RestTemplateConfig {

    //关键:使用RestTemplateBuilder,不要用new RestTemplate()
    @Bean
    @Profile("test")//仅测试环境生效
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        ClientHttpRequestFactory requestFactory = SSLIgnoreConfig.insecureRequestFactory();

        return builder.requestFactory(()->requestFactory).build;
    }
}
csharp 复制代码
private void testPostRequest() {
        System.out.println("\n=== Testing POST Request ===");
        HttpHeaders headers = new HttpHeaders();
        headers.set("key", "test-key");
        headers.set("secret", "test-secret");
        headers.setContentType(MediaType.APPLICATION_JSON);
        
        String requestBody = "{"test":"data"}";
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
        
        try {
            ResponseEntity<String> response = restTemplate.exchange(
                "https://httpbin.org/post",
                HttpMethod.POST,
                entity,
                String.class
            );
            System.out.println("POST Response: " + response.getBody());
        } catch (Exception e) {
            System.err.println("POST Error: " + e.getMessage());
        }
    }
相关推荐
寒草2 分钟前
「寒草呈献」工作六年,是否仍有创造未来的勇气 ✨
前端·后端
程序员爱钓鱼23 分钟前
为什么学习 Go?Go 能做什么?
后端·面试·go
程序员爱钓鱼1 小时前
Rust 切片 Slice 详解:安全访问连续数据
前端·后端·rust
咖啡八杯9 小时前
GoF设计模式——解释器模式
java·后端·spring·设计模式
掘金码甲哥9 小时前
这块终端神器, 必须吹爆!
后端
糖果店的幽灵9 小时前
【DeepAgents 从入门到精通】Context Management 上下文管理
java·人工智能·后端·spring·中间件·langgraph·deepagents
Csvn10 小时前
📊 SQL 入门 Day 8:集合操作 — 用 SQL 做数学里的"并交差"
后端·sql
码事漫谈12 小时前
告别数据孤岛与AI“水土不服”:金仓多模融合时序库如何让数据真正服务于业务
后端
IT_陈寒13 小时前
Redis的持久化配置把我坑惨了:你以为数据安全了?
前端·人工智能·后端
星栈13 小时前
Node 接口该写同步还是异步?
后端·node.js