问题描述
我正在尝试制作Android应用程序,可以在其中获取和解析HTML(从没有API的网站).我正在使用OkHttp.该站点具有不受信任(但有效)的证书.我得到了:
I am trying to make Android app, where I can get and parse HTML (from site which doesnt have API). I am using OkHttp. The site has untrusted (but valid) certificate. I am getting:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
我已经设置了官方方式( https://developer .android.com/training/articles/security-ssl#java ),现在我需要将其与OkHttpClient链接.
I've already set up the official way (https://developer.android.com/training/articles/security-ssl#java) and now I need to link it with OkHttpClient.
我尝试过
OkHttpClient client = new OkHttpClient;
OkHttpClient.Builder builder = client.newBuilder();
builder.sslSocketFactory(sslcontext.getSocketFactory()).build();
但是它不起作用,也已弃用.谢谢
But it doesnt work, and also it is deprecated.Thanks
推荐答案
仅用于调试.使用此代码意味着信任任何证书,就像完全不使用https一样.
您需要使用不推荐使用的sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)
.
You need to use sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)
which is not deprecated.
使用此变量(它将创建不验证证书链的信任管理器):
Use this variable (which creates a trust manager that does not validate certificate chains):
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]);
还将其应用于验证每个主机:
also apply this to verify every host:
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
这篇关于向OkHttp客户端添加自定义证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!