package com.vincent.rsf.openApi.utils; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import javax.net.ssl.*; import java.io.IOException; import java.net.HttpURLConnection; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; /** * SSL工具类,用于创建忽略SSL证书验证的RestTemplate */ public class SslUtils { /** * 创建忽略SSL证书验证的RestTemplate * * @return RestTemplate实例 */ public static RestTemplate createIgnoreSSLRestTemplate() { try { // 创建信任所有证书的TrustManager TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // 安装信任所有证书的TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // 创建HttpsURLConnection的工厂 HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); // 创建跳过主机名验证的HostnameVerifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // 安装跳过主机名验证的HostnameVerifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); // 创建自定义的ClientHttpRequestFactory SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory() { @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); ((HttpsURLConnection) connection).setHostnameVerifier(allHostsValid); } super.prepareConnection(connection, httpMethod); } }; // 创建RestTemplate并设置工厂 RestTemplate restTemplate = new RestTemplate(factory); return restTemplate; } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new RuntimeException("Failed to create SSL RestTemplate", e); } } }