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
Lis开发者_如何转开发t <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();
}
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.
精彩评论