我正在尝试制作Android应用程序,在那里我可以获取并解析HTML(来自没有API的网站).我正在使用OkHttp.该站点具有不受信任(但有效)的证书.我正进入(状态:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
我已经设置了官方方式(https://developer.android.com/training/articles/security-ssl#java),现在我需要将它与OkHttpClient链接.
我试过了
OkHttpClient client = new OkHttpClient;
OkHttpClient.Builder builder = client.newBuilder();
builder.sslSocketFactory(sslcontext.getSocketFactory()).build();
但它不起作用,也被弃用了.
谢谢
解决方法:
您需要使用未弃用的sslSocketFactory(SSLSocketFactory sslSocketFactory,X509TrustManager信任管理器).
使用此变量(创建不验证证书链的信任管理器):
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
并以这种方式传递给sslSocketFactory():
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
也适用于验证每个主机:
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});