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 } } } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章