javax.net.ssl.SSLPeerUnverifiedException:peer未经过身份验证的问题

时间:2016-06-13 16:52:42

标签: java apache-httpclient-4.x

我正在使用HttpClient-4.2.1并已在服务器上添加了证书,但我仍然遇到错误。

我已经阅读了现有问题,说要添加TrustManager(X509TrustManager),但根据我的想法,这不是解决方案。如果我错了,请纠正我。

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

at sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:397)

at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)

at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:572)

at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:180)

at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294)

at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:640)

at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:479)

at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)

at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)

at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)

1 个答案:

答案 0 :(得分:1)

您可以使用此代码。希望它能解决你的问题。

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
......
private static HttpClient getHttpClient() {

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        sslContext.init(null,
                new TrustManager[]{new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {

                        return null;
                    }

                    public void checkClientTrusted(
                            X509Certificate[] certs, String authType) {

                    }

                    public void checkServerTrusted(
                            X509Certificate[] certs, String authType) {

                    }
                }}, new SecureRandom());

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);



        HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build();

        return httpClient;

    } catch (Exception e) {
        e.printStackTrace();
        return HttpClientBuilder.create().build();
    }
}

将不再抛出异常,当认证过期时,浏览器将发出有关过期证书的警告并让用户确认。

资源链接:

  1. Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated