HttpMethod.releaseConnection()用法

时间:2012-08-14 06:02:10

标签: java httpclient

我正在使用带有MultiThreadedHttpConnectionManager的HttpClient 3..0.1并使用以下代码获取页面并获取该页面的最终重定向网址。

多个线程并行访问此代码。运行此代码一段时间后,我开始持续获取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)

每次执行方法后我是否需要调用get.releaseConnection()?或者目前的编码没问题?

1 个答案:

答案 0 :(得分:1)

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

您应该在此代码中只保留一个实例,并在全局try / finally中最后清理它。