本文将展示如何配置Apache HttpClient 4和5以支持“接受所有”SSL。
目标很简单——访问没有有效证书的HTTPS URL。
SSLPeerUnverifiedException
在未配置SSL的情况下,尝试消费一个HTTPS URL时会遇到以下测试失败:
@Test
void whenHttpsUrlIsConsumed_thenException() {
String urlOverHttps = "https://localhost:8082/httpclient-simple";
HttpGet getMethod = new HttpGet(urlOverHttps);
assertThrows(SSLPeerUnverifiedException.class, () -> {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(getMethod, new CustomHttpClientResponseHandler());
assertThat(response.getCode(), equalTo(200));
});
}
具体的失败信息是:
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:126)
...
当无法为URL建立有效的信任链时,就会抛出javax.net.ssl.SSLPeerUnverifiedException
异常。
配置SSL - 接受所有(HttpClient 5)
现在让我们配置HTTP客户端以信任所有证书链,无论其有效性如何:
@Test
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk() throws GeneralSecurityException, IOException {
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
final