码迷,mamicode.com
首页 > Web开发 > 详细

httpclient4使用说明

时间:2018-04-11 19:11:23      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:httpclient4   java   

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使用说明

标签:httpclient4   java   

原文地址:http://blog.51cto.com/chend/2097087

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!