Exception when using HttpClient to execute GET after POST

I am using Apache DefaultHttpClient()with a method execute(HttpPost post)to do http POST. With this I went to the site. Then I want to use the same client to do HttpGet. But when I do this, I get an exception:

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

I am not sure why this is happening. Any help would be appreciated.

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();


}
+3
source share
1 answer

This is because, after POST, the connection manager still maintains a connection with the POST response. You need to do this before you can use the client for anything else.

:

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

GET.

+2

Source: https://habr.com/ru/post/1785614/


All Articles