Я пытаюсь принимать все сертификаты и/или принимать собственные сертификаты с использованием Apache HTTPClient версия 4.5 (учебник ссылки here)Игнорировать самозаверенные сертификаты в Apache HTTPClient 4,5
Я был используя решения этой проблемы из кучки сообщений на SO. Пока никто из них не работал.
Я получаю эту ошибку: Error while trying to execute request. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
Apache Docs:
- Apache v4.5 tutorial
- SSL/TLS customization
- Apache has a guide для версии 3, но не версия 4.
Связанные StackOverflow Questions - Вот некоторые ссылки решений я попробовал:
- Ignoring SSL certificate in Apache HttpClient 4.3
- How to ignore SSL certificate errors in Apache HttpClient 4.0
- Ignore SSL Certificate Errors with Java
- Need to trust all the certificates during the development using Spring
- How to handle invalid SSL certificates with Apache HttpClient?
Обратите внимание, что во всех этих примерах я также передаю хранилище файлов cookie и поставщик учетных данных прокси-сервера, которые я определил ранее. Они работают, я просто пытаюсь добавить поддержку SSL.
Try # 1
Создать свой собственный контекст Ssl с SSLContextBuilder
и доверять всю самоподписывающуюся стратегии с TrustSelfSignedStrategy
.
SSLContextBuilder sshbuilder = new SSLContextBuilder();
sshbuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sshbuilder.build());
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.setDefaultCookieStore(cookieStore)
.setSSLSocketFactory(sslsf)
.build();
РЕЗУЛЬТАТ: Не работает. Получил Error while trying to execute request. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
Try # 2
То же, что и выше, но добавить PoolingHttpClientConnectionManager
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new PlainConnectionSocketFactory())
.register("https", sslsf)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(2000);//max connection
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.setDefaultCookieStore(cookieStore)
.setSSLSocketFactory(sslsf)
.setConnectionManager(cm)
.build();
РЕЗУЛЬТАТ: Не работает. Got Error while trying to execute request. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
Try # 3
Просто принимать все сертификаты переопределением TrustStrategy
(это не рекомендуется)
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.setDefaultCookieStore(cookieStore)
.setSSLSocketFactory(sslsf)
.build();
РЕЗУЛЬТАТ: Не работает.Получил Error while trying to execute request. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
Try # 4
я нашел что-то полезное из this answer:
As of version 4.5 HttpClient disables SSLv3 protocol version by default
Вот решение, которое он дал:
SSLContext sslcontext = SSLContexts.createSystemDefault();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslcontext, new String[] { "TLSv1", "SSLv3" }, null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", sslConnectionSocketFactory)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.setDefaultCookieStore(cookieStore)
.setSSLSocketFactory(sslConnectionSocketFactory)
.setConnectionManager(cm)
.build();
РЕЗУЛЬТАТ: Не работает. Получил Error while trying to execute request. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
Решение
Это довольно неудобно, но мне просто нужно изменить порт при подключении к SSL:
//For HTTPS
HttpHost httpstarget = new HttpHost("mysite.com", 443, "https");
//For HTTP
HttpHost httptarget = new HttpHost("mysite.com", 80, "http");
Да, вы правы. Я просто попытался перейти на фактический сайт, и я думаю, что он не работает, они, возможно, работали все это время – Kayvar