views:

290

answers:

1

In an Android app, I am using one static instance of org.apache.http.impl.client.DefaultHttpClient and sharing that instance in all activities and services of the app, so that this client may be used to log in once to a remote server and all subsequent user requests to that remote server will remain authenticated.

Every activity or Service that makes a GET or POST to this remote server calls the same method : MyUtilityClass.gettHttpClient()

Do I need to worry about synchronization of this httpclient? If so, what is the best way to handle this?

+2  A: 

Use a ThreadSafeConnectionManager, then you do not need to synchronize.

CommonsWare
I triedyour suggestion and implemented it as per this question:http://stackoverflow.com/questions/3003010/is-this-a-good-implementation-of-defaulthttpclient-and-threadsafeclientconnmanageWhen I use this I get thread deadlock! When I change it to not use the threadSafeClientConnectionManager by initializing httpclient like this httpclient = new DefaultHttpClient(params);Then, I do NOT ever get deadlocks. So what is going on here? I am left thinking that ThreadSafeConnectionManager is problematic..at least on Android 1.5
Ok, when I added setMaxConnectionsPerRoute to 20 that seems to have resolved my deadlock issue. I am a little confused as to which version of HttpClient I should be using. Many posts say that Android is using 4.x, but I am developing to Android 1.5 and I believe I have version 3.X. Would appreciate your comments. Thanks.
@johnrock: Android has only ever had HttpClient 4.x.
CommonsWare
Thanks. Sorry for my confusion. I think my confusion comes from the fact that, I suspect, the ThreadSafeClientConnManager in Android is from HttpClient 3, while the DefaultHttpClient if from HttpClient 4. Is that right? Because the constructor for TSCCM in Android, ThreadSafeClientConnManager(HttpParams params, SchemeRegistry schreg), is deprecated in HttpClient 4. Am I missing something or is this a bit confusing?
@johnrock: the `ThreadSafeClientConnManager` in Android is from HttpClient 4.x. http://hc.apache.org/httpcomponents-client-4.0.1/httpclient/apidocs/index.html
CommonsWare
I apologize in advance for continuing to be an idiot. I am trying to overcome this. I beleive you are right - just trying to understaind why these two links have me confused:http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/ThreadSafeClientConnManager.html"This class is derived from MultiThreadedHttpConnectionManager in HttpClient 3"ANd this one:http://hc.apache.org/httpcomponents-client/httpclient/apidocs/org/apache/http/impl/conn/tsccm/ThreadSafeClientConnManager.htmlWhich says it is since version 4.0, and this is the one that has the deprecated constructor
@johnrock: I have no idea.
CommonsWare