HttpClientUtil

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClientUtil相关的知识,希望对你有一定的参考价值。

import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; public class HttpClientUtil { private HttpClientUtil() { } private static HttpClient httpClient = null; //静态工厂方法 public static HttpClient getInstanceHttpClient() { if (httpClient == null) { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); // 创建 HttpClient 的多线程实例 //在创建httpclient对象的时候,默认使用simpleHttpConnectionManager作为连接管理,而它不适合多线程环境。故修正方法是:自己创建httpclient对象,并指定适合多线程环境的连接管理器。 // httpClient = new HttpClient(connectionManager); // /* HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setConnectionTimeout(1000); // params.setSoTimeout(2000); // 最大连接数 params.setMaxTotalConnections(1); params.setDefaultMaxConnectionsPerHost(1); params.setStaleCheckingEnabled(true); connectionManager.setParams(params); HttpClientParams httpClientParams = new HttpClientParams(); // 设置httpClient的连接超时,对连接管理器设置的连接超时是无用的 httpClientParams.setConnectionManagerTimeout(1000); //等价于4.2.3中的CONN_MANAGER_TIMEOUT httpClient = new HttpClient(connectionManager); httpClient.setParams(httpClientParams); //另外设置http client的重试次数,默认是3次;当前是禁用掉(如果项目量不到,这个默认即可) // httpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); // */ } return httpClient; } }

以上是关于HttpClientUtil的主要内容,如果未能解决你的问题,请参考以下文章