OkHttp關於https請求的設定

yangxi_001發表於2017-06-20

https請求由於證照驗證問題,直接請求一般都會失敗.一般是做證照驗證處理或者忽略證照驗證,這裡介紹後者.解決方案從外文文章中看到,這裡搬磚一下.希望對大家有幫助

[java] view plain copy
  1. private static OkHttpClient getUnsafeOkHttpClient() {  
  2.         try {  
  3.             // Create a trust manager that does not validate certificate chains  
  4.             final TrustManager[] trustAllCerts = new TrustManager[] {  
  5.                     new X509TrustManager() {  
  6.                         @Override  
  7.                         public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {  
  8.                         }  
  9.   
  10.                         @Override  
  11.                         public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {  
  12.                         }  
  13.   
  14.                         @Override  
  15.                         public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
  16.                             return new java.security.cert.X509Certificate[]{};  
  17.                         }  
  18.                     }  
  19.             };  
  20.   
  21.             // Install the all-trusting trust manager  
  22.             final SSLContext sslContext = SSLContext.getInstance("SSL");  
  23.             sslContext.init(null, trustAllCerts, new java.security.SecureRandom());  
  24.             // Create an ssl socket factory with our all-trusting manager  
  25.             final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();  
  26.   
  27.             OkHttpClient.Builder builder = new OkHttpClient.Builder();  
  28.             builder.sslSocketFactory(sslSocketFactory);  
  29.             builder.hostnameVerifier(new HostnameVerifier() {  
  30.                 @Override  
  31.                 public boolean verify(String hostname, SSLSession session) {  
  32.                     return true;  
  33.                 }  
  34.             });  
  35.   
  36.             OkHttpClient okHttpClient = builder.build();  
  37.             return okHttpClient;  
  38.         } catch (Exception e) {  
  39.             throw new RuntimeException(e);  
  40.         }  
  41.     }  
[java] view plain copy
  1. 在最新的Okhttp中 以前是要返回null  現在改成返回一個空的陣列就可以了  
  2. new java.security.cert.X509Certificate[]{}  

相關文章