muchumanoj
muchumanoj

Reputation: 125

connection persistence using httpclient

i do multiple request to the same url using httpclient.execute(request). Can I re-use the connection for the consecutive requests? how can i optimise the code without declaring HttpClient again and again.

for(int i=0;i<=50;i++)
{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("my_url");
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
}

Upvotes: 3

Views: 5650

Answers (2)

Jwalin Shah
Jwalin Shah

Reputation: 2521

try below.

HttpUriRequest httpGet = new HttpGet(uri);
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

In order to use a single client in your code (based on Exception using HttpRequest.execute(): Invalid use of SingleClientConnManager: connection still allocated and Lars Vogel Apache HttpClient - Tutorial):

  • Step 1. Move the client generation outside the for-loop.
  • Step 2. You should read the response content and close the stream. If you don't do this you will get the following exception

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

In code:

//step 1
HttpClient client = new DefaultHttpClient();
for(int i=0;i<=50;i++) {
    HttpGet request = new HttpGet("my_url");
    HttpResponse response = client.execute(request);
    System.out.println(response.getStatusLine().getStatusCode());
    //step 2
    BufferedReader br = new BufferedReader(
        new InputStreamReader(response.getEntity().getContent()));
    //since you won't use the response content, just close the stream
    br.close();
}

Upvotes: 8

Related Questions