Which of the httpurlconnection and Apache Defaulthttpclient is recommended to use in Android?

Source: Internet
Author: User

In Android, the way to request network resources includes the following: HttpURLConnection and Apache defaulthttpclient. So, which of these two ways is more recommended to use? What is the reason why the official Android docs recommend httpurlconnection for us?

On Android 4.0, a response cache (response buffer) has been added for HttpURLConnection, which is a good mechanism to reduce the number of HTTP requests The reason Android officially recommends using HttpURLConnection instead of Apache defaulthttpclient is to use httpurlconnection not only to make HTTP requests optimized for Android, The Reponse Cache has also been added on 4.0, which further increases efficiency.

Let's take a look at an official example: use the reflection mechanism to open the HTTP response cache.

private void Enablehttpresponsecache () {  try {    long httpcachesize = ten * 1024x768 * 1024x768;//MiB    File HttpCache Dir = new File (Getcachedir (), "http");    Class.forName ("Android.net.http.HttpResponseCache")         . GetMethod ("Install", File.class, Long.class)         . Invoke (null, Httpcachedir, httpcachesize);  } catch (Exception httpresponsecachenotavailable) {    log.d (TAG, "HTTP response cache is unavailable.");}  }


The above example enables the response cache to be opened on Android 4.0 or more devices without affecting the previous program. After the cache is turned on, all HTTP requests in the cache can be answered directly in the local store, and when Android needs to request the same resources, through the cache, there is no need to open a new network connection to get the resources. and the cache response can be ensured by the server is not expired, which can effectively reduce the bandwidth, and the response is not cached by the convenience of the next request to be stored in the response cache.


Which of the httpurlconnection and Apache Defaulthttpclient is recommended to use in Android?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.