Is this a good implementation of DefaultHttpClient and ThreadSafeClientConnManager in Android?

Posted by johnrock on Stack Overflow See other posts from Stack Overflow or by johnrock
Published on 2010-06-09T03:59:16Z Indexed on 2010/06/09 4:02 UTC
Read the original article Hit count: 1071

Filed under:
|

In my Android app I am sharing one httpclient for all activities/threads. All requests are made by callling getHttpClient().execute(httpget) or getHttpClient().execute(httppost).

Is this implementation complete/correct and safe for multiple threads? Is there anything else missing i.e. Do I have to worry about releasing connections at all?

private static  HttpClient httpclient ;


public static HttpClient getHttpClient() {

if(httpclient == null){ return getHttpClientNew(); } else{ return httpclient; } }

public static synchronized HttpClient getHttpClientNew() {

    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF_8");

HttpProtocolParams.setUseExpectContinue(params, false);
HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));


    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

 httpclient = new DefaultHttpClient(cm, params);  

return httpclient; }

This is an example of how the httpclient is used:

private void update() {

HttpGet httpget = new HttpGet(URL); httpget.setHeader(USER_AGENT, userAgent); httpget.setHeader(CONTENT_TYPE, MGUtils.APP_XML);

HttpResponse response;

  try {
       response = getHttpClient().execute(httpget);
       HttpEntity entity = response.getEntity();                     

          if (entity != null) {

           // parse stuff

          }

  }      
  catch (Exception e) {

  }

}

© Stack Overflow or respective owner

Related posts about android

Related posts about httpclient