0

我正在使用 HttpClient 3..0.1MultiThreadedHttpConnectionManager并使用以下代码来获取页面并获取该页面的最终重定向 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() 吗?还是当前的编码很好?

4

1 回答 1

1

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

您应该在此代码中只保留一个实例,并在全局 try/finally 中将其清理干净。

于 2012-08-14T06:19:20.717 回答