1.概述

本文将展示如何将Apache HttpClient 4配置为“接受所有”SSL支持。目标是简单 - 消耗没有有效证书的HTTPS URL。

如果你想更深入地研究并学习其他可以用HttpClient做的很酷的事情,请转到主要的HttpClient指南

进一步阅读:

HttpClient连接管理

如何打开、管理和关闭与Apache HttpClient 4的连接。

高级的HttpClient配置

高级用例的HttpClient配置。

HttpClient 4 -发送自定义Cookie

如何使用Apache HttpClient 4发送自定义cookie。

2.这SSLPEERUNVERIFIEDException.

没有配置SSLHttpClient,以下测试 - 消耗HTTPS URL - 将失败:

public class RestClientLiveManualTest {@Test(expected = SSLPeerUnverifiedException.class) public void当httppsurlisconsumed_thenexception()抛出ClientProtocolException, IOException {CloseableHttpClient httpClient = HttpClients.createDefault();String urlOverHttps = "https://localhost:8082/httpclient-simple";getMethod = new HttpGet(urlOverHttps);HttpResponse response = httpClient.execute(getMethod);为了(response.getStatusLine () .getStatusCode(),等于(200);}}

确切的失败是:

javax.net.ssl.sslpeerunverifiedException:对等体未在sun.security.ssl.sslsessionimpl.getpeercertificates(sslsessionimpl.java:397)上验证org.apache.http.conn.ssl.abstractverifier.verify(abstractworverifier.java:126)。..

javax.net.ssl.SSLPeerUnverifiedException例外只要无法为URL建立有效的信任链时就会发生。

3.配置SSL - 接受全部(HttpClient <4.3)

现在让我们配置HTTP客户端来信任所有的证书链,而不管它们的有效性:

@test public final void voidedacceptallcertificates_whenhttpsurlisconsumed_thenok()抛出generalsecurityexception {httpcomponentsclienthttperpertivefactory letuctory = new http componentsclienthttpertproestfactory();关闭的httpclient httpclient =(closeablehttpclient)cenucefactory.gethttpclient();truststrategy接受矩=(证书,authtype) - > true;sslsocketfactory sf = new sslsocketfactory(AcceptingTruststrategy,Allow_All_Hostname_verifier);httpclient.getConnectionManager()。GetSchemeregistry()。注册(新方案(“HTTPS”,8443,SF));ResponseEntity response = new RestTemplate(requestFactory)。Exchange(Urloverhttps,httpmethod.get,null,string.class);为了(response.getStatusCode () value(),等于(200);}

与新TrustStrategy现在重写标准证书验证过程(应该咨询配置的信任管理器) - 测试现在通过和客户端能够消耗HTTPS URL

4.配置SSL -接受所有(HttpClient 4.4及以上)

有了新的HTTPClient,现在我们有了一个增强的、重新设计的默认SSL主机名验证器。还带着介绍SSLConnectionSocketFactory注册表,它很容易构建SSLsocketfactory。所以我们可以写下上面的测试用例,如:

@Test公共最终void voidedAllCertificates_Whenhttpsurlisconsumed_thenok()抛出generalsecurityexception {truststrategy接受轨道=(cert,authtype) - > true;sslcontext sslcontext = sslcontexts.custom()。loadTrustMaterial(Null,AcceptingTruststrategy).build();SSLConnectionSocketFactory SSLSF =新SSLConnectionSocketFactory(SSLContext,NoophostNameVerifier.Instance);Registry  SocketFactoryRegistry = RegistryBuilder。 create().register(“https”,sslsf).register(“http”,new plainconnectionsocketfortory()).build();BasichTtpClientConnectionManager ConnectionManager = New BasichttpClientConnectionManager(SocketFactoryRegistry);CloseAbrehttpclient httpclient = httpclient.custom()。setslsocketfactory(sslsf).setConnectionManager(ConnectionManager).build();httpcomponentsclienthttprokeStfactory请求从属= nem httpponentsClienthttpRequestFactory(httpclient);analesstity  response = new resttemplate(请求等待).exchange(Urloverhttps,httpmethod.get,null,string.class);为了(response.getStatusCode () value(),等于(200);}

5.春天创建RestTemplate使用SSL(HttpClient <4.3)

现在我们已经看到了如何配置RAWHttpClient使用SSL支持,让我们来看看一个更高级别的客户 - 春天创建RestTemplate

没有配置SSL,以下测试按预期失败:

@Test(expected = ResourceAccessException.class) public void whenHttpsUrlIsConsumed_thenException() {String urlOverHttps = "https://localhost:8443/httpclient-simple/api/bars/1";ResponseEntity response = new RestTemplate()。交易所(urlOverHttps HttpMethod。获取、零String.class);为了(response.getStatusCode () value(),等于(200);}

因此,让我们配置SSL:

@Test public void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenException() throws GeneralSecurityException {HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();DefaultHttpClient httpClient = (DefaultHttpClient) requestFactory.getHttpClient();TrustStrategy acceptingTrustStrategy = (cert, authType) -> true SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, ALLOW_ALL_HOSTNAME_VERIFIER);httpClient.getConnectionManager().getSchemeRegistry() .register(新方案(“https”,8443,sf));String urlOverHttps = "https://localhost:8443/httpclient-simple/api/bars/1";ResponseEntity response = new RestTemplate(requestFactory)。Exchange(Urloverhttps,httpmethod.get,null,string.class);为了(response.getStatusCode () value(),等于(200);}

如你所见,这是这与我们为原始HttpClient配置SSL的方式非常相似-我们用SSL支持配置请求工厂,然后通过这个预配置工厂来实例化模板。

6.春天创建RestTemplate使用SSL(HttpClient 4.4)

我们可以用同样的方法来配置创建RestTemplate

@test public void taveacceptingAllCertificateSusing4_4_WhenusingRestTemplate_thencorRect()抛出client client procolexception,ioException {closeablehttpclient httpclient = httpclient.custom().setsslhostnameverifier(new noophostnameverifier()).build();build();httpcomponentsclienthttprokeStfactory请求从属= new http componentsclienthttpropestfactory();请求.SethttpClient(httpclient);analesstity  response = new resttemplate(请求等待).exchange(Urloverhttps,httpmethod.get,null,string.class);为了(response.getStatusCode () value(),等于(200);}

7.结论

本教程讨论了如何为Apache HttpClient配置SSL,以便它能够使用任何HTTPS URL,而不管证书是什么。弹簧的配置是一样的创建RestTemplate也说明了。

然而,要理解的重要一点是此策略完全忽略证书检查- 这使它不安全,只使用它有意义的地方。

可以找到这些示例的实施GitHub项目- 这是一个基于Eclipse的项目,因此应该易于导入和运行。

通用底部

使用Spring 5和Spring Boot 2开始,通过学习春天课程:

>>查看课程
18.评论
最古老的
最新的
内联反馈
查看所有评论
本文评论关闭!