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

3
我使用Apache的DefaultHttpClient()execute(HttpPost post)方法进行http POST请求,以登录网站。 然后我想使用同一个客户端来发出HttpGet请求。 但是当我这样做时,会出现异常:

Exception in thread "main" java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated.

我不确定为什么会出现这种情况。希望能得到帮助。
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();


}

请参见:https://dev59.com/AW445IYBdhLWcg3w9O0s - Kai Sternad
1个回答

2
这是因为在POST之后,连接管理器仍然持有POST响应连接。在您可以将客户端用于其他操作之前,您需要让它释放该连接。
这样做应该有效:
HttpResponse postResponse = client.execute(post);
EntityUtils.consume(postResponse.getEntity();

然后,您就可以执行GET请求了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接