首先,源代码中没有注释。
org.apache.hc.core5.ssl.SSLContextBuilder#loadTrustMaterial(org.apache.hc.core5.ssl.TrustStrategy)
public SSLContextBuilder loadTrustMaterial(
final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {
return loadTrustMaterial(null, trustStrategy);
}
这是会触发混淆行为的代码,它与 apache 官方演示Apache Demo相同
@Test
void customStrategy() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, IOException, ParseException {
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
sslContextBuilder.loadTrustMaterial((chain, authType) -> false);
SSLContext sslcontext = sslContextBuilder.build();
SSLConnectionSocketFactoryBuilder sslConnectionSocketFactoryBuilder = SSLConnectionSocketFactoryBuilder.create();
sslConnectionSocketFactoryBuilder.setSslContext(sslcontext);
sslConnectionSocketFactoryBuilder.setTlsVersions(TLS.V_1_2);
SSLConnectionSocketFactory sslConnectionSocketFactory = sslConnectionSocketFactoryBuilder.build();
PoolingHttpClientConnectionManagerBuilder poolingHttpClientConnectionManagerBuilder = PoolingHttpClientConnectionManagerBuilder.create();
poolingHttpClientConnectionManagerBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
HttpClientConnectionManager httpClientConnectionManager = poolingHttpClientConnectionManagerBuilder.build();
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setConnectionManager(httpClientConnectionManager);
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpClientContext clientContext = HttpClientContext.create();
CloseableHttpResponse response = closeableHttpClient.execute(new HttpGet("https://www.baidu.com"), clientContext);
System.out.println("BODY-Length " + EntityUtils.toString(response.getEntity()).length());
SSLSession sslSession = clientContext.getSSLSession();
System.out.println(sslSession.getPeerHost() + ":" + sslSession.getPeerPort());
}
输出是:
... ...
BODY-Length 2443
www.baidu.com:443
即使我直接返回false
我的自定义 TrustStrategy。
sslContextBuilder.loadTrustMaterial((chain, authType) -> {
throw new CertificateException();
});
那会中断连接,但是我不认为接口返回false,而是仅在异常正确使用时才中断。
问题:为什么 return false 不起作用?Thorw execption 让我感觉不对,这是设计的吗?