Drejc
Drejc

Reputation: 14286

DefaultHttpClient keep alive connection on multiple requests

I'm using the DefaultHttpClient to make numerous requests to the same URL with basic authentication.

Something like this:

for (String json: listOfItems)
{
    DefaultHttpClient client = new DefaultHttpClient();

    try
    {       
       client.getCredentialsProvider().setCredentials(
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "basic"),
                    new UsernamePasswordCredentials(user, pass));

       HttpPost request = new HttpPost(path);
       setHeaders(request);

       StringEntity se = new StringEntity(json, HTTP.UTF_8);
       se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
       request.setEntity(se);

       client.execute(request);    
    }       
    finally
    {
       // close/release connection
       client.getConnectionManager().shutdown();            
    }
}

My question is what is the best way to keep alive the connection while doing this. So I don't need to close the connection on each post request.

Upvotes: 3

Views: 7032

Answers (1)

rbot
rbot

Reputation: 259

You might need to add the Socket_Timeout parameter and implement a KeepAlive strategy, which are detailed over here -

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e652

Upvotes: 1

Related Questions