<< [HttpClient]HTTPClient PostMethod 中文乱码问题解决方案(2种) - 追竹 - 博客频道 - CSDN.NET | 首页 | 使用Mahout为布尔型数据生成推荐内容 >>

Craig Andrews » Best way to use HttpClient in Android

Google不鼓励使用HttpClient,更喜欢使用HttpURLConnection和HttpsURLConnection。

Many Android applications access the Internet resources over HTTP (and my projects are no exception). There are 2 common ways to do that: use Apache HttpClient 4.x (which is included in Android) or use HttpURLConnection (from Java). Google stated in a September 29, 2011 blog post that they prefer you use HttpURLConnection, but many apps and a large number of Java libraries already use HttpClient and won’t be changing soon (if ever). So HttpClient is here to stay.

With that in mind, the performance and footprint of HttpClient can vary widely based on how its set up. Here are my recommendations:

  • Always use one HttpClient instance for your entire application. HttpClient is not free to instantiate – each additional instance takes time to create and uses more memory. However, more importantly, using one instance allows HttpClient to pool and reuse connections along with other optimizations that can make big differences in how your application performs.
  • Use a thread safe connection manager. If you’re using one global HttpClient, it will be accessed by multiple threads concurrently – so if you don’t use a thread safe connection manager, Bad Things will happen.
  • Use Android’s android.net.SSLCertificateSocketFactory and android.net.SSLSessionCacheif they’re available. Using these instead of the base HttpClient SSLSocketFactorywill reduce round trips when connecting to the same https site multiple times, making your application feel faster.
  • Set the user agent to something useful. That way, the server’s logs will be far more useful, which may save you (or someone else) a lot of time later if (when) a problem occurs.

With all that said, here’s how I get my global HttpClient instance. This code should work on all Android versions (it should even work all the way back to 1.0 – if anyone cares). I use Google Guice‘s Provider interface and injection to get the application, but you can easily adopt this to a form that doesn’t use Guice.

阅读全文……

标签 : ,



发表评论 发送引用通报