本文同步至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