Apache httpclient建立了很多连接

时间:2010-07-01 18:15:41

标签: java apache-httpclient-4.x

我正在使用apache httpclient 4.0通过http连接到视频流(motion jpeg)。这是我的代码:

DefaultHttpClient client;

HttpParams params = new BasicHttpParams();

List<String> authpref = new ArrayList<String>();
authpref.add(AuthPolicy.DIGEST);
authpref.add(AuthPolicy.BASIC);

params.setParameter("http.auth.proxy-scheme-pref", authpref);
params.setParameter("http.protocol.handle-authentication", Boolean.TRUE);

SchemeRegistry schemeRegistry = new SchemeRegistry();

schemeRegistry.register(
    new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

ClientConnectionManager connectionManager =
    new ThreadSafeClientConnManager(params, schemeRegistry);

client = new DefaultHttpClient(connectionManager, params);

client.getCredentialsProvider().setCredentials(
     new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
     new UsernamePasswordCredentials(username, password));

HttpResponse videoResponse = client.execute(new HttpGet(url));

问题是client.execute()行似乎与视频流建立了数百个连接。我可以通过登录到服务器并执行netstat来看到这一点:端口80的连接数量非常大,而且它们都处于TIME_WAIT状态。

我在这里做错了吗?发生了什么事?

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

如果您没有将连接释放回池和/或为每个请求创建新的连接池,那么会发生这种情况。

http://hc.apache.org/httpcomponents-client-4.0.1/tutorial/html/connmgmt.html