前置知识
需要对证书认证有所了解。
访问https接口
使用httpClient访问比如百度的首页时,这是一个https协议的地址,由于JDK内置了一些大型CA机构的公钥证书(根证书),所以httpClient会信任这些CA机构颁发的证书,程序能够正常访问。
当访问自签证书的接口时,就需要客户端自己对服务器进行校验了。
操作系统也有内置的证书,但是无法影响java程序。
httpclient配置
以httpclient 的4.5.3版本为例,配置代码如下:
SSLContext sslContext = null;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(null, (cert, authType) -> true).build();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
}
SSLConnectionSocketFactory sslConFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslContext);
如果配置了连接池,配置代码如下:
SSLContext sslContext = null;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(null, (cert, authType) -> true).build();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
}
SSLConnectionSocketFactory sslConFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConFactory)
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 20
cm.setDefaultMaxPerRoute(20);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm);
当使用连接池时,配置稍有不同。