因为公司最近需求 ,需要由之前的http升级到https 为了省钱,采用了自建证书进行升级,后台配置好证书发布之后,安卓端访问报错
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. 未找到证书路径的信任锚。意思就是没有相关的信任证书,网上找了一大堆方法,最后的处理方法是 在程序的初始化的时候 在Application里面加入信任所有证书的代码。
/**
* Enables https connections
*/
@SuppressLint("TrulyRandom")
public static void handleSSLHandshake() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
// 返回true才能实现https访问 默认为false
return true;
}
});
} catch (Exception ignored) {
}
}
然后问题得到了解决!!!