我将HttpClient 3..0.1与MultiThreadedHttpConnectionManager
一起使用,并使用以下代码来获取页面,并获得该页面的最终重定向URL。
多个线程并行访问此代码。运行这段代码一段时间后,我开始连续获取ConnectionPoolTimeoutException
,然后没有进一步提取任何页面。
这是否与我应该增加的connectionManagerParam
值有关,或者我在代码中做错了什么?
GetMethod get = null;
try {
get = new GetMethod();
get.setURI(uri);
get.setFollowRedirects(false);
int status = httpClient.executeMethod(null, get, new HttpState());
String location = null;
int retry = 2;
if (get.getResponseHeader("location") != null) {
location = get.getResponseHeader("location").getValue();
}
while (retry > 0 && ((int) (status / 100) != 2) && ((int) (status / 100) == 3) && location.length() > 0) {
// To get the final redirected url.
uri = URLUtil.createAbsoluteURIWithFix(location, null);
get = new GetMethod();
get.setURI(uri);
get.setFollowRedirects(false);
status = httpClient.executeMethod(null, get, new HttpState());
if (get.getResponseHeader("location") != null) {
location = get.getResponseHeader("location").getValue();
}
retry--;
}
if (status == 200) {
uri = get.getURI();
String html = URLUtil.getResponseBodyAsString(get, charsets);
}
} catch (Exception e) {
} finally {
if (get != null) {
get.releaseConnection();
}
}
异常stackTrace
org.apache.commons.httpclient.ConnectionPoolTimeoutException: Timeout waiting for connection
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.doGetConnection(MultiThreadedHttpConnectionManager.java:490)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.getConnectionWithTimeout(MultiThreadedHttpConnectionManager.java:394)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:152)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)
我需要在每个execute方法之后调用get.releaseConnection()吗?还是目前的编码还可以?
最佳答案
似乎您没有关闭第一个get并创建一个对相同var影响的新对象。
并循环做同样的事情。
您应该在此代码中仅保留一个实例,并在全局try / final中最后将其清除。
关于java - HttpMethod.releaseConnection()的用法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11946577/