Spring中restTemplate忽略https证书的代码实现

 package myapp.util;
 
 import org.jetbrains.annotations.NotNull;
 import org.springframework.http.client.SimpleClientHttpRequestFactory;
 import org.springframework.web.client.RestTemplate;
 
 import javax.net.ssl.HttpsURLConnection;
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.TrustManager;
 import javax.net.ssl.X509TrustManager;
 import java.io.IOException;
 import java.net.HttpURLConnection;
 import java.net.Proxy;
 import java.security.KeyManagementException;
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
 import java.security.cert.X509Certificate;
 
 /**
  * @author zhangyalong
  * @version 2019-03-24 19:19
  */
 public class HttpClientUtils {
 
     public static RestTemplate getInstance(Proxy proxy, int connTimeout, int readTimeout, boolean enableSslCheck) {
         final RestTemplate restTemplate = new RestTemplate();
 
         // sslIgnore
         SimpleClientHttpRequestFactory requestFactory;
         if (!enableSslCheck) {
             requestFactory = getUnsafeClientHttpRequestFactory();
         } else {
             requestFactory = new SimpleClientHttpRequestFactory();
         }
 
         // proxy
         if (proxy != null) {
             requestFactory.setProxy(proxy);
         }
 
         // timeout
         requestFactory.setConnectTimeout(connTimeout);
         requestFactory.setReadTimeout(readTimeout);
 
         restTemplate.setRequestFactory(requestFactory);
         return restTemplate;
     }
 
     private static SimpleClientHttpRequestFactory getUnsafeClientHttpRequestFactory() {
         TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {
 
             public X509Certificate[] getAcceptedIssuers() {
                 return new X509Certificate[0];
             }
 
             public void checkClientTrusted(X509Certificate[] chain, String authType) {
             }
 
             public void checkServerTrusted(X509Certificate[] chain, String authType) {
             }
         }};
         final SSLContext sslContext;
         try {
             sslContext = SSLContext.getInstance("TLS");
             sslContext.init(null, byPassTrustManagers, new SecureRandom());
             sslContext.getSocketFactory();
         } catch (NoSuchAlgorithmException | KeyManagementException e) {
             throw new RuntimeException(e);
         }
 
         return new SimpleClientHttpRequestFactory() {
             @Override
             protected void prepareConnection(HttpURLConnection connection,
                                              @NotNull String httpMethod) throws IOException {
                 super.prepareConnection(connection, httpMethod);
                 if (connection instanceof HttpsURLConnection) {
                     ((HttpsURLConnection) connection).setSSLSocketFactory(
                             sslContext.getSocketFactory());
                 }
             }
         };
     }
 
     public static RestTemplate getInstance(Proxy proxy, boolean enableSsLCheck) {
         return getInstance(proxy, -1, -1, enableSsLCheck);
     }
 
 }
要在使用 RestTemplate忽略证书,你可以创建一个自定义的 RestTemplate 实例,并配置一个自定义的 HttpClient 来处理 SSL 验证。以下是一个示例: ```java import org.apache.http.client.HttpClient; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.cert.X509Certificate; public class CustomRestTemplate { public static RestTemplate createRestTemplate() throws Exception { // 创建信任所有证书的 SSLContext SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} }}, null); // 创建忽略证书验证的 HttpClient HttpClient httpClient = HttpClients.custom() .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setSSLContext(sslContext) .build(); // 使用自定义的 HttpClient 创建 HttpComponentsClientHttpRequestFactory HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); // 创建 RestTemplate 实例并设置请求工厂 RestTemplate restTemplate = new RestTemplate(requestFactory); return restTemplate; } public static void main(String[] args) { try { RestTemplate restTemplate = createRestTemplate(); // 使用忽略证书RestTemplate 发送请求 String response = restTemplate.getForObject("https://example.com/api", String.class); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述示例,我们创建了一个自定义的 RestTemplate 实例 `restTemplate`,该实例使用了一个自定义的 HttpClient,该 HttpClient 忽略证书验证。你可以根据自己的需求修改 `createRestTemplate` 方法代码,并使用 `restTemplate` 对象来发送 HTTP 请求。请注意,忽略证书验证可能会带来安全风险,请慎重使用。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值