异常--- SingleClientConnManager:仍然分配连接

时间:2012-01-10 17:10:51

标签: java httpclient

我有一个代码来读取页面的响应。它看起来像这样。

public static void main(String[] args)
    {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpEntity entity  = null;
        try{

            String it= "https://www.aaa/login";
                HttpPost httpost = new HttpPost(it);

                List <NameValuePair> ln= new ArrayList <NameValuePair>();
                ln.add(new BasicNameValuePair("un", "aaa"));
                ln.add(new BasicNameValuePair("pwd", "bbb"));
                httpost.setEntity(new UrlEncodedFormEntity(ln, HTTP.UTF_8));

                HttpResponse  response = httpclient.execute(httpost);
                entity  = response.getEntity();
                GZIPInputStream gis= new GZIPInputStream(entity.getContent());
            StringBuffer st = new StringBuffer();
                for (int c = gis.read(); c != -1; c = gis.read()) {
                    st.append((char)c);
                }

                    CookieStore cookieStore = httpclient.getCookieStore();
                    HttpContext httpContext = new BasicHttpContext();
                    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
                    HttpGet httpget = new HttpGet("http://aaa/index");
                    HttpResponse httpResponse = httpclient.execute(httpget, httpContext);
                    entity = httpResponse.getEntity();

                    if (entity != null) {
                        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
                        String readLine;
                        while(((readLine = br.readLine()) != null)) {
                          System.err.println("br   :"+readLine);
                    }


                }                
        }catch(Exception e){
            e.printStackTrace();
        }
        finally{

            EntityUtils.consume(entity);
            httpclient.getConnectionManager().shutdown();
        }

当我运行这个程序时,我得到了foll异常。

java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
    at org.apache.http.impl.conn.SingleClientConnManager.getConnection(SingleClientConnManager.java:216)
    at org.apache.http.impl.conn.SingleClientConnManager$1.getConnection(SingleClientConnManager.java:190)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:401)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)

我已关闭finally块中的连接。正如在其他线程中所建议的那样,我在重用连接之前已经使用了响应主体。还有什么会出错?

1 个答案:

答案 0 :(得分:2)

之前

HttpResponse httpResponse = httpclient.execute(httpget, httpContext);

你还需要

EntityUtils.consume(entity);