POST后使用HttpClient执行GET时出现异常

时间:2011-01-15 13:59:27

标签: java httpclient http-post http-get

我使用Apache的DefaultHttpClient()execute(HttpPost post)方法进行http POST。 有了这个我登录到一个网站。 然后我想使用同一个客户端来制作HttpGet。 但是当我这样做时,我得到一个例外:

  

线程“main”中的异常java.lang.IllegalStateException:无效使用SingleClientConnManager:仍然分配了连接。

我不确定为什么会这样。任何帮助将不胜感激。

public static void main(String[] args) throws Exception {

    // prepare post method
    HttpPost post = new HttpPost("http://epaper02.niedersachsen.com/epaper/index_GT_neu.html");

    // add parameters to the post method
    List <NameValuePair> parameters = new ArrayList <NameValuePair>();
    parameters.add(new BasicNameValuePair("username", "test"));
    parameters.add(new BasicNameValuePair("passwort", "test")); 

    UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
    post.setEntity(sendentity); 

    // create the client and execute the post method
    HttpClient client = new DefaultHttpClient();
    HttpResponse postResponse = client.execute(post);
    //Use same client to make GET (This is where exception occurs)
    HttpGet httpget = new HttpGet(PDF_URL);
    HttpContext context = new BasicHttpContext();

    HttpResponse getResponse = client.execute(httpget, context);



    // retrieve the output and display it in console
    System.out.print(convertInputStreamToString(postResponse.getEntity().getContent()));
    client.getConnectionManager().shutdown();


}

1 个答案:

答案 0 :(得分:2)

这是因为在POST之后,连接管理器仍然保持POST响应连接。在将客户端用于其他目的之前,您需要先将其发布。

这应该有效:

HttpResponse postResponse = client.execute(post);
EntityUtils.consume(postResponse.getEntity();

然后,您可以执行GET。

相关问题