---
title: "HTTPClient的多线程编程"
author: "liboqi"
date: "2012-03-02T09:09:43Z"
tags: []
categories: ["编程语言"]
slug: "httpclient"
draft: false
lastmod: "2012-03-02T09:09:43Z"
id: 1435142
url: "https://liboqi.iteye.com/blog/1435142"
---

Axis2的连接主要采用了HttpClient进行与服务器的服务的交互，其中的代码分析看出Httpclient的多线程支持代码的编写，记录下来，便于以后用到使用

 

```
 protected HttpClient getHttpClient(MessageContext msgContext) {
        HttpClient httpClient;
        final ConfigurationContext configContext = msgContext.getConfigurationContext();
        synchronized (lock) {
            httpClient = (HttpClient) configContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT);
            if (httpClient == null) {
                log.trace("Making new ConnectionManager");
                HttpConnectionManager connManager = new MultiThreadedHttpConnectionManager();

                // In case we need to set any params, do it here, but for now use defaults.
//                HttpConnectionManagerParams params = new HttpConnectionManagerParams();
//                params.setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, 200);
//                etc...
//                connManager.setParams(params);

                httpClient = new HttpClient(connManager);
                HttpClientParams clientParams = new HttpClientParams();
                // Set the default timeout in case we have a connection pool starvation to 30sec
                clientParams.setConnectionManagerTimeout(30000);
                httpClient.setParams(clientParams);
                configContext.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
            }

            // Get the timeout values set in the runtime
            initializeTimeouts(msgContext, httpClient);
        }
        return httpClient;
    }
```

 

MultiThreadedHttpConnectionManager就是用来解决线程安全性的，HttpClient自动维护他们的关系

其中MultThreadedHttpConnectionManage有如下r参数配置：

 

connectionStaleCheckingEnabled：这个标志对所有已经创建的connections都适用。除特殊情况外，此值应该设置成true。

maxConnectionsPerHost：最大连接数，默认是2。

maxTotalConnections：最大活动连接数，默认是20

所以可以根据具体需要调整参数的大小

**特别注意**

    在使用完成了连接以后一定需要手动关闭连接，由于他自己无法进行自动连接释放，所以需要手动释放连接。