在 Java 中请求 URL 时忽略证书错误

2022-01-25 00:00:00 ssl-certificate java

我正在尝试打印一个 URL(根本不涉及浏览器),但该 URL 当前正在抛出以下内容:

I'm trying to print a URL (without having a browser involved at all) but the URL is currently throwing the following:

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

我使用 JEditorPane 的 setPage 方法调用 URL,该方法仅将 URL 作为参数.假设我无法更改任何服务器端并且我仍然需要访问此资源,我将如何忽略证书错误(或其他使我达到目标的东西)?

I'm calling the URL using a JEditorPane's setPage method, which just takes a URL as a parameter. Assuming I can't change anything server side and I still need to get to this resource, how would I go about ignoring the certificate error (or something else that gets me to my goal)?

通过浏览器访问此 URL 告诉我该站点不受信任,并询问我是否要继续.

Accessing this URL via a browser tells me the site is untrusted and asks me if I want to proceed.

推荐答案

扩展 JEditorPane 以覆盖 getStream() 方法.

Extend JEditorPane to override the getStream() method.

在该方法中,您可以 打开一个 URLConnection. 测试它是否是一个 HttpsURLConnection.如果是,初始化 你的 拥有 SSLContext 和自定义 X509TrustManager 不执行任何 检查. 获取上下文的 SSLSocketFactory 和 将其设置为连接的套接字工厂.然后返回 InputStream 来自连接.

Inside that method, you can open a URLConnection. Test whether it is an HttpsURLConnection. If it is, initialize your own SSLContext with a custom X509TrustManager that doesn't perform any checks. Get the context's SSLSocketFactory and set it as the socket factory for the connection. Then return the InputStream from the connection.

这将阻止运行时为保护用户免受提供恶意软件的欺骗性站点的任何尝试.如果那是真的你想要的…

This will defeat any attempts by the runtime to protect the user from a spoof site serving up malware. If that's really what you want…

相关文章