您的位置:首页 > 理论基础 > 计算机网络

CloseableHttpAsyncClient忽略https的证书验证

2017-06-26 15:05 661 查看
https比http安全是因为,网络通信协议里边有数字签名和证书等概念

阮一峰写的科普文解释数字签名:http://www.ruanyifeng.com/blog/2011/08/what_is_a_digital_signature.html

使用apache httpclient客户端api忽略证书验证代码:

初始化连接池客户端:

private static PoolingNHttpClientConnectionManager pool;

private static CloseableHttpAsyncClient httpAsyncClient = null;

static {
try {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// don't check
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// don't check
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, null);
SSLIOSessionStrategy sslioSessionStrategy = new SSLIOSessionStrategy(sslContext, SSLIOSessionStrategy.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry<SchemeIOSessionStrategy> registry = RegistryBuilder.<SchemeIOSessionStrategy>create()
.register("http", NoopIOSessionStrategy.INSTANCE)
.register("https", sslioSessionStrategy)
.build();
ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
pool = new PoolingNHttpClientConnectionManager(ioReactor,registry);
pool.setMaxTotal(100); // 设置最多连接数
pool.setDefaultMaxPerRoute(20); // 设置每个host最多20个连接数
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(12000) // 设置请求响应超时时间
.setConnectTimeout(12000) // 设置请求连接超时时间
.build();

httpAsyncClient = HttpAsyncClients.custom().setConnectionManager(pool) // 设置连接池
.setDefaultRequestConfig(requestConfig) // 设置请求配置
.build();
httpAsyncClient.start();
} catch (Exception e) {
e.printStackTrace();
}

}

调用post
HttpPost post = new HttpPost(url); // 创建POSt请求
// 设置参数到请求对象中
post.setEntity(new StringEntity(parames, encoding));
if (StringUtil.isNotEmpty(host)) {
post.setHeader("Host", host);
}
// 执行请求操作,并拿到结果(异步)
Future<HttpResponse> resultFuture = httpAsyncClient.execute(post, null);// 设置请求参数
HttpResponse response = resultFuture.get(timeout, TimeUnit.MILLISECONDS);
LogUtil.info("asyn post cost",url,parames,System.currentTimeMillis() - start);
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null)
result = EntityUtils.toString(httpEntity, encoding);
https://hc.apache.org/httpcomponents-asyncclient-dev/quickstart.html
其中execute使用FutureCallback<HttpResponse> callback参数和不使用区别没搞懂,感觉异步方法都是reactor模型实现的异步阻塞。在等待返回结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息