Fix CertPathValidatorException: Trust anchor for certification path not found.

Android AUmaWSsSoi 5个月前 (04-17) 307次浏览 0个评论

问题:

之前的一个开源项目碰到了一个问题,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


java问与答 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:http://javaexception.com/archives/30
喜欢 (1)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址