Apache Http客户端SSL证书错误

时间:2014-07-13 06:00:29

标签: java ssl https httpclient apache-httpclient-4.x

我知道之前有人问过,但我尝试了我发现的所有解决方案,但仍然无效。

基本上,我正在尝试通过Apache Http Client(4.3)获取一些内容,而我正在连接的网站存在一些SSL问题。

首先,我收到了SSLExceptionunrecognized_name消息。我试图通过将jsse.enableSNIExtension属性设置为false来解决此问题。

然后,我得到了这个例外: 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

然后我尝试提供我接受所有证书的赢得SSLFactory,但我仍然得到相同的例外。这是我的代码:

private static void sslTest() throws Exception {
    System.setProperty("jsse.enableSNIExtension", "false");

    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, new TrustSelfSignedStrategy())
            .useTLS()
            .build();

    SSLConnectionSocketFactory connectionFactory =
            new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());

    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);

    CloseableHttpClient httpclient = HttpClients.custom()
            .setSSLSocketFactory(connectionFactory)
            .setDefaultCookieStore(cookieStore)
            .build();

    URI uri = new URIBuilder()
            .setScheme("https")
            .setHost(BASE_URL)
            .build();

    String responseBody = httpclient.execute(new HttpGet(uri), RESPONSE_HANDLER);
}

非常感谢所有帮助!

4 个答案:

答案 0 :(得分:12)

请注意,信任自签名证书并不意味着信任任何证书。尝试以这种方式设置SSL上下文:

SSLContext sslContext = SSLContexts.custom()
        .loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
                return true;
            }
        })
        .useTLS()
        .build();

请注意,通常信任证书不加区别地首先违背了使用SSL的目的。在绝对必要时使用或仅用于测试

答案 1 :(得分:9)

在Http Client 4.5.2中:

    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, new TrustStrategy() {

                @Override
                public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
                    return true;
                }
            })
            .build();

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslContext,
            NoopHostnameVerifier.INSTANCE);

然后:

HttpClientBuilder builder = HttpClients.custom().setSSLSocketFactory(sslsf);

答案 2 :(得分:1)

您的信任库不信任服务器证书。

允许所有主机名是一个HTTPS步骤,只有在证书可信的情况下才能调用

答案 3 :(得分:0)

以下是Apache 4x信任所有内容

<md-form-field>
    <input type="text">
</md-form-field>