Java okHttp 3 忽略Https的SSL最佳方案


okHttp是Java平台下方便的HTTP客戶端工具,最近筆者在實際項目中使用時,發現於客戶第三方應用集成時,對方提供的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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM