在请求自定义证书网站是会出现: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 异常,原因在于在当前ca管理器中并未匹配到当前证书所对应的ca文件,而谁做的校验呢?
//操作来源于此处的check
public interface X509TrustManager extends TrustManager {
void checkClientTrusted(X509Certificate[] var1, String var2) throws CertificateException;
void checkServerTrusted(X509Certificate[] var1, String var2) throws CertificateException;
X509Certificate[] getAcceptedIssuers();
}
既然如此只要绕过此处的check便可以解决此处问题。下面是okhttp的使用方式。
X509TrustManager tm = 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[]{};
}
}
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient okHttp = new OkHttpClient().newBuilder()
.sslSocketFactory(sslSocketFactory , tm)
.build();
使用此方法跳过ca证书的校验