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?