java - 忽略 Servlet 中的 SSL 证书

标签 java tomcat ssl sslhandshakeexception

我收到以下异常:

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

我做了一些研究并更改了我的连接代码:

SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

CloseableHttpClient client = HttpClients.custom()
            .setRedirectStrategy(new LaxRedirectStrategy()) 
            .setSslcontext(sslContext)   
            .setConnectionManager(connMgr)
            .build();

到目前为止,这解决了问题,我不再收到异常并且连接正常。

当我在 Tomcat 中运行的 Servlet 中使用相同的代码时,问题再次出现。

为什么?

最佳答案

试试下面的代码。

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class DummyX509TrustManager implements X509TrustManager {

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }

    @Override
    public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
            throws CertificateException {
    }

    @Override
    public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
            throws CertificateException {
    }
};


final TrustManager[] trustAllCerts = new TrustManager[] { new DummyX509TrustManager() };
try {
    SSLContext sslContext= SSLContext.getInstance("SSL"); 
    sslContext.init(null, trustAllCerts, null);

    CloseableHttpClient client = HttpClients.custom()
        .setRedirectStrategy(new LaxRedirectStrategy()) 
        .setSslcontext(sslContext)   
        .setConnectionManager(connMgr)
        .build();
} catch (KeyManagementException e) {
    throw new IOException(e.getMessage());
} catch (NoSuchAlgorithmException e) {
    throw new IOException(e.getMessage());
}

关于java - 忽略 Servlet 中的 SSL 证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33394361/

相关文章:

带 SSL 的 WCF- 找不到本地主机

tomcat - 如何在 Tomcat 7.0 中设置 Web 应用程序的上下文路径

jsf - com.sun.faces.config.InitFacesContext.cleanupInitMaps 中的空指针异常

java - 如何在java中打印星形图案?

java - JPA错误: without eclipselink

jsf - Tomcat JSF 错误

java - 通过 Fiddler 捕获 Java https 并获取 javax.net.ssl.SSLHandshakeException

通过 SSL 连接时 MySQL 客户端连接有延迟

java - 两个已知地理坐标之间沿线的多个点?

java - 根据使用的构建版本选择Gradle属性