Showing posts with label httpclient. Show all posts
Showing posts with label httpclient. Show all posts

Sunday, August 14, 2011

HTTPComponents client 4.1.2 >>> Invalid use of SingleClientConnManager: connection still allocated

In most of the ideal case scenarios single inialization of DefaultHttpClient will serve the purpose. However this singleton implementaion approach can lead to some problems. Since the resource designed as Singleton pattern becomes effectively global, doing things like modifying the time out value, or forcibly closing the connection manager (as one commenter pointed out), could lead to the HttpClient to be in an invalid or undesired state when reused at a different time or in a differentscenario in the same application.

Luckily, after much surfing I stumbled upon Jason Hudgin’s site where he created a convenience method that avoids this problem.
To overcome this the modified basic implemntaion will lead to something written below:

public static DefaultHttpClient getThreadSafeClient() {

DefaultHttpClient httpClient = new DefaultHttpClient();
ClientConnectionManager mgr = httpClient.getConnectionManager();
HttpParams params = httpClient .getParams();

httpClient = new DefaultHttpClient(
new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);

return httpClient ;
}

The right place to use something like this is when you want to download multiple items from a single remote machine, for example, if you need to make concurrent requests to any service on server to download image or do any CRUD operation and all requests sharing one HttpClient instance, reusing HTTP connections as they became available.