sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target.
时间: 2023-07-01 15:29:36 浏览: 78
该异常表示在建立SSL连接时,Java程序无法找到有效的证书路径。这通常是因为目标服务器的证书不被信任或未被信任的颁发机构(CA)签名。
解决此问题的方法有以下几种:
1. 将目标服务器的证书导入Java信任存储区,以便Java程序信任它。可以使用keytool命令将证书导入Java信任存储区。
2. 临时信任目标服务器的证书。可以使用以下代码:
```
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
```
这将创建一个信任所有证书的TrustManager,然后将其设置为默认的SSLSocketFactory。
请注意,第二种方法是不安全的,因为它会信任所有证书,包括恶意证书。建议使用第一种方法。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)