httpclient4使用说明
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了httpclient4使用说明相关的知识,希望对你有一定的参考价值。
public class HttpClientObject {
public org.apache.http.client.HttpClient httpClient4New;// = new HttpClient();
public static HttpClient buildHttpClient() {
// builder.setProxy(new HttpHost("127.0.0.1",8888));
return builder.build();
}
//为HttpClient增加跳过SSL证书验证
private static PoolingHttpClientConnectionManager newConnectionManager() {
SSLContext sslcontext = null;
try {
sslcontext = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslcontext.init(null, new TrustManager[] { tm }, null);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE))
.build();
SocketConfig config = SocketConfig.custom().setSoTimeout(1000 * 60).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(20000);
cm.setDefaultMaxPerRoute(20000);
cm.setDefaultSocketConfig(config);
return cm;
}
catch (Exception e1) {
e1.printStackTrace();
}
return null;
}
private static PoolingHttpClientConnectionManager poolCm = null;
static {
poolCm = newConnectionManager();
new IdleConnectionMonitorThread(poolCm).start();
}
private static final RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(1000 * 10)
.setConnectionRequestTimeout(1000 * 10).setSocketTimeout(1000 * 60).build();
private static final HttpClientBuilder builder = HttpClients.custom().setConnectionManager(poolCm)
.setDefaultRequestConfig(defaultRequestConfig);
/**
* 定时清理连接池中失效的连接
*/
private static class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
this.setDaemon(true);
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 30 sec
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
}
catch (InterruptedException ex) {
// terminate
}
}
}
}
以上是关于httpclient4使用说明的主要内容,如果未能解决你的问题,请参考以下文章