本文同步至http://javaexception.com/archives/30 問題: 之前的一個開源項目碰到了一個問題,Fix CertPathValidatorException: Trust anchor for certification path not found. 問題在於自建後臺 ...
本文同步至http://javaexception.com/archives/30
問題:
之前的一個開源項目碰到了一個問題,Fix CertPathValidatorException: Trust anchor for certification path not found.
問題在於自建後臺的站點用的是免費的ssl證書,okhttp預設會進行https簽名校驗,所以需要去掉這種校驗。
解決辦法:
OkHttpClient.Builder builder = new OkHttpClient.Builder(); final TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } } }; try { final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]); builder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } catch (Exception e) { e.printStackTrace(); } builder.connectTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS); OkHttpClient client = builder.build();
鏈接如下:
https://github.com/leanote/leanote-android/commit/52ff2e80a3d900fd6804dd69a8da82a68474c9ce
這個開源項目也值得學習下 https://github.com/leanote/leanote-android