配置 Apache HttpClient 信任所有 SSL 证书
1、概览 本文将带你了解如何配置 Apache HttpClient 4 和 5 以支持 “Accept All”(接受所有)SSL。目标很简单 - 信任所有证书,包括无效的 SSL 证书。
2、SSLPeerUnverifiedException 如果不在 HttpClient 上配置 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 建立有效的信任链(Trust Chain),就会出现 javax.net.ssl.SSLPeerUnverifiedException 异常。
3、配置 SSL - Accept All(HttpClient 5) 现在,配置 HTTP 客户端信任所有证书链,无论其是否有效: