Apache HttpClient错误:javax.net.ssl.SSLPeerUnverifiedException:对等方未经过身份验证

时间:2016-05-26 14:41:09

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

我尝试配置org.apache.http.client.HttpClient以使用https。这是客户端配置:

TrustManager[] trustManagers = new TrustManager[] { new DummyTrustManager() };

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);

SSLSocketFactory sf = new SSLSocketFactory(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

Scheme scheme = new Scheme("https", 443, sf);
SchemeRegistry registry = new SchemeRegistry();
registry.register(scheme);

ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(registry);

DefaultHttpClient client = new DefaultHttpClient(cm, httpParameters);

这是DummyTrustManager的代码:

public static class DummyTrustManager implements X509TrustManager {

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

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

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

当我发送请求时,我得到了

 `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`

可能是什么问题?

1 个答案:

答案 0 :(得分:1)

您还需要调整TrustStrategy

TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
    @Override
    public boolean isTrusted(X509Certificate[] certificate, String authType) {
        return true;
    }
};
SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
...

http://www.baeldung.com/httpclient-ssl

上查看完整示例