Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception when using HttpClient to execute GET after POST

I use Apache's DefaultHttpClient() with the execute(HttpPost post) method to make a http POST. With this I log on to a website. Then I want to use the same Client to make a HttpGet. But when I do, I get an Exception:

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

I am not sure as to why this occurs. 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();


}
like image 850
tzippy Avatar asked Sep 02 '26 10:09

tzippy


1 Answers

This is because after the POST, the connection manager is still holding on to the POST response connection. You need to make it release that before you can use the client for something else.

This should work:

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

Then, you can execute your GET.

like image 196
skaffman Avatar answered Sep 04 '26 01:09

skaffman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!