Java okHttp 3 忽略SSH的最佳方案


okHttp是Java平台下方便的Restful客户端工具,最近笔者在实际项目中使用时,发现于客户第三方应用集成时,对方提供的API采用自签名的HTTPS,直接导致项目运行报错,并且客户方面因为经常变更证书,要求忽略证书,为解决该问题,笔者在网络上搜索现成的方案,并不能完全满足自己的业务需求或对代码的轻度洁癖。

参考部分网络上浏览量较高的方案,笔者在其思路引领下进行修改。废话不多说,直接贴代码。

代码 1. 工具类 OkHttpUtil.java

 1 import java.security.KeyManagementException;
 2 import java.security.NoSuchAlgorithmException;
 3 import java.security.SecureRandom;
 4 import java.security.cert.X509Certificate;
 5 
 6 import javax.net.ssl.HostnameVerifier;
 7 import javax.net.ssl.SSLContext;
 8 import javax.net.ssl.SSLSession;
 9 import javax.net.ssl.TrustManager;
10 import javax.net.ssl.X509TrustManager;
11 
12 /**
13  * 
14  * @author Vania
15  *
16  */
17 public class OkHttpUtil {
18     /**
19      * X509TrustManager instance which ignored SSL certification
20      */
21     public static final X509TrustManager IGNORE_SSL_TRUST_MANAGER_X509 = new X509TrustManager() {
22         @Override
23         public void checkClientTrusted(X509Certificate[] chain, String authType) {
24         }
25 
26         @Override
27         public void checkServerTrusted(X509Certificate[] chain, String authType) {
28         }
29 
30         @Override
31         public X509Certificate[] getAcceptedIssuers() {
32             return new X509Certificate[] {};
33         }
34     };
35 
36     /**
37      * Get initialized SSLContext instance which ignored SSL certification
38      * 
39      * @return
40      * @throws NoSuchAlgorithmException
41      * @throws KeyManagementException
42      */
43     public static SSLContext getIgnoreInitedSslContext() throws NoSuchAlgorithmException, KeyManagementException {
44         var sslContext = SSLContext.getInstance("SSL");
45         sslContext.init(null, new TrustManager[] { IGNORE_SSL_TRUST_MANAGER_X509 }, new SecureRandom());
46         return sslContext;
47     }
48 
49     /**
50      * Get HostnameVerifier which ignored SSL certification
51      * 
52      * @return
53      */
54     public static HostnameVerifier getIgnoreSslHostnameVerifier() {
55         return new HostnameVerifier() {
56             @Override
57             public boolean verify(String arg0, SSLSession arg1) {
58                 return true;
59             }
60         };
61     }
62 }

代码 2 业务代码片段

1 client = new OkHttpClient()
2      .newBuilder()
3      .sslSocketFactory(OkHttpUtil.getIgnoreInitedSslContext().getSocketFactory(), OkHttpUtil.IGNORE_SSL_TRUST_MANAGER_X509)
4      .hostnameVerifier(OkHttpUtil.getIgnoreSslHostnameVerifier())
5      .build();