gpt4 book ai didi

java - HttpMethod.releaseConnection() 用法

转载 作者:行者123 更新时间:2023-12-01 15:13:40 25 4
gpt4 key购买 nike

我将 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();
}
}

异常堆栈跟踪

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)

我需要在每个执行方法之后调用 get.releaseConnection() 吗?或者当前的编码没问题?

最佳答案

似乎您没有关闭第一个 get 并创建一个影响同一个 var 的新 get 。在循环中做同样的事情。

您应该在此代码中仅保留一个实例,并在全局 try/finally 结束时清理它。

关于java - HttpMethod.releaseConnection() 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11946577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com