PoolingHttpClientConnectionManager的官方介绍:
PoolingHttpClientConnectionManager
是个更复杂的类,它管理着连接池,可以同时为很多线程提供http连接请求。Connections are pooled on a per route basis.当请求一个新的连接时,如果连接池有有可用的持久连接,连接管理器就会使用其中的一个,而不是再创建一个新的连接。
PoolingHttpClientConnectionManager
维护的连接数在每个路由基础和总数上都有限制。默认,每个路由基础上的连接不超过2个,总连接数不能超过20。在实际应用中,这个限制可能会太小了,尤其是当服务器也使用Http协议时。
当使用了请求连接池管理器(比如PoolingClientConnectionManager
)后,HttpClient就可以同时执行多个线程的请求了。
PoolingClientConnectionManager
会根据它的配置来分配请求连接。如果连接池中的所有连接都被占用了,那么后续的请求就会被阻塞,直到有连接被释放回连接池中。为了防止永远阻塞的情况发生,我们可以把http.conn-manager.timeout
的值设置成一个整数。如果在超时时间内,没有可用连接,就会抛出ConnectionPoolTimeoutException
异常。
import java.util.Map;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
public class HttpClientUtil {
private static PoolingHttpClientConnectionManager cm = null;
private static CloseableHttpClient httpClient = null;
static {
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
// .register("https", sslsf)
.register("http", PlainConnectionSocketFactory.INSTANCE).build();
cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(20);
cm.setValidateAfterInactivity(1000);
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000)
.setConnectionRequestTimeout(20000).build();
httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(defaultRequestConfig)
.build();
}
public static CloseableHttpClient getHttpClient() {
// httpClient不能被关闭 ,如果关闭 连接池也会被关闭,就会抛出连接池关闭异常
// httpClient只有生成一个实例对接就可以了,因为他执行请求方法时,会去从连接池去连接
// 源码:final ConnectionRequest connRequest =
// connManager.requestConnection(route, null);
return httpClient;
}
private static void addRequestHeader(HttpUriRequest request, Map<String, String> headerMap) {
if (headerMap == null) {
return;
}
for (String headerName : headerMap.keySet()) {
if ("Content-Length".equalsIgnoreCase(headerName)) {
continue;
}
String headerValue = headerMap.get(headerName);
request.addHeader(headerName, headerValue);
}
}
}
测试:
public class TestHttClient {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClientUtil.getHttpClient();
// 请求方式和访问路径
HttpPost httpPost = new HttpPost("http://localhost:8280/IRGDD/system/hGDeviceSmokeDetectorController/findList");
// 传送内容 以及内容格式和编码
httpPost.setEntity(new StringEntity("", ContentType.APPLICATION_JSON));
try {
CloseableHttpResponse execute = httpClient.execute(httpPost);
HttpEntity entity = execute.getEntity();
// 默认编码Ios
String s = EntityUtils.toString(entity);
System.out.println(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
官网实例
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager.
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1); //必须关掉
} finally {
response1.close();//必须关掉
}
HttpPost httpPost = new HttpPost("http://targethost/login");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response2.close();
}