Java中HTTPS连接时出现PKIX path building failed错误——如何修复?
大家好!我正在编写一个Java小应用,需要通过HTTPS向外部REST API发送GET请求。我使用的是标准的HttpURLConnection。代码很简单,但执行时抛出异常:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
这是我的代码:
URL url = new URL("https://example.com/api/data");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
int responseCode = conn.getResponseCode(); // 这里出错
我已经检查过:URL正确,网站可以在浏览器中访问。但Java无法建立受信任的连接。我是Java新手,不明白如何解决这个问题。我谷歌过——有人提到keystore、truststore,但这太复杂了。有没有简单的方法?还是必须处理证书?感谢帮助!