解决 PKIX path building failed: && unable to find valid certification path to requested target
·
问题
java 项目 访问 https url 时报错
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
原因
HTTPS 域名的公钥证书不在 JDK/JRE 的证书库中,被Java认为是不可信的。
解决办法一:
添加证书 (亲测有效)
1、下载目标网站是 ssl 证书
放在某个目录下,并重名 为xxx.cer
2、手动安装到
进入 jdk 的 /bin 目录下
keytool -import -keystore "%JAVA_HOME%\jre\lib\security\cacerts" -file D:\websitename.cer -alias websitename
# keytool其它命令:
# 删除websitename证书:
keytool -delete -alias websitename -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -storepass changeit
#查看cacerts中的所有证书:
keytool -list -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -storepass changeit
口令输入:changeit
然后选择:Y
安装完成
重启你的服务,就能访问目标网站了 (https)
解决办法二:
代码忽略(亲测,没生效,有空了再看看)
public static void ignoreSsl() throws Exception {
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
public static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements TrustManager, X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
}
更多推荐
已为社区贡献7条内容
所有评论(0)