is Android accessing the network, using HttpURLConnection or httpclient?

Source: Internet
Author: User

Recently in the study of the source code of the volley framework, found that it is more interesting in the use of HTTP requests, in Android 2.3 and later, using the HttpURLConnection, and in Android 2.2 and below, using the httpclient. I am also more curious about the reasons for this use, so specifically found a Google engineer wrote a blog, the text of HttpURLConnection and httpclient in contrast, I will give you a brief translation.

Original address: http://android-developers.blogspot.com/2011/09/androids-http-clients.html

Most Android applications use the HTTP protocol to send and receive network data, while Android provides two main ways to do HTTP operations, HttpURLConnection and HttpClient. Both of these methods support HTTPS protocol, upload and download in streams, configure timeout, IPv6, and connection pooling.

HttpClient

Defaulthttpclient and its brother Androidhttpclient are httpclient specific implementation classes, they all have a lot of APIs, and the implementation is relatively stable, the number of bugs is very small.

But at the same time, because the HttpClient API is too numerous, it makes it difficult to upgrade and expand it without breaking compatibility, so the Android team is not actively working on upgrading and optimizing httpclient.

HttpURLConnection

HttpURLConnection is a versatile, lightweight HTTP client that can be used for HTTP operations for most applications. Although the HttpURLConnection API provides a relatively simple, it also makes it easier to use and extend it.

But before the Android 2.2 version, HttpURLConnection has been having some annoying bugs. For example, when you call the Close () method on a readable inputstream, it is possible to invalidate the connection pool. Then our usual solution is to disable the connection pooling function directly:

1 2 3 4 5 6 private  void  disableConnectionReuseIfNecessary() {        // 这是一个2.2版本之前的bug        if  (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {              System.setProperty( "http.keepAlive" "false" );        } }

In the Android 2.3 version, we added more transparent response compression. The httpurlconnection automatically adds the following message header to each request and processes the corresponding return result:
Accept-encoding:gzip
Configure your Web server to support the ability to compress the response of the client, so that you can gain maximum benefit from this improvement. If there is a problem compressing the response, this document will tell you how to disable it.
However, if the function of response compression is activated, the content-length in the HTTP response header will represent the compressed length, then using the Getcontentlength () method to remove the extracted data is wrong. The correct approach should be to always call the Inputstream.read () method to read the response data until it appears 1.
We've also added some improvements to HTTPS in the Android 2.3 version, and now Httpsurlconnection will connect using SNI (Server Name indication). Enables multiple HTTPS hosts to share the same IP address. In addition, a number of compression and session mechanisms have been added. If the connection fails, it will automatically attempt to reconnect. This allows httpsurlconnection to connect to the latest servers more efficiently without compromising the compatibility of older versions.
In the Android 4.0 release, we added some caching mechanisms for the response. When the cache is installed (call Httpresponsecache's Install () method), all HTTP requests will meet the following three scenarios:
All cached responses are provided by local storage. Because there is no need to initiate a network connection request for a task, all responses are immediately available.
Depending on the situation, the cache response must have a server for the update check. For example, the client initiates a request like "if/foo.png this picture has changed, send it to me", the server needs to return the updated data, or return a 304 not modified state. If the requested content does not occur, the client will not download any data.
Responses that are not cached are provided directly by the server. This part of the response is stored later in the response cache.
Since this feature is only available after 4.0, we can usually use reflection to start the response caching feature. The following example code shows how to enable the response cache feature in Android 4.0 and later, without affecting the previous version:

1 2 3 4 5 6 7 8 9 10 privatevoidenableHttpResponseCache() {        try{             longhttpCacheSize =  10 1024 1024 // 10 MiB             File httpCacheDir =  newFile(getCacheDir(),  "http" );             Class.forName( "android.net.http.HttpResponseCache" )                         .getMethod( "install" , File. class long . class )                         .invoke( null , httpCacheDir, httpCacheSize);        catch(Exception httpResponseCacheNotAvailable) {        } }

You should also configure your Web server to include a cached message header on the HTTP response.

Which one is the best?

Prior to the Android 2.2 version, HttpClient had fewer bugs, so using it was the best option.

HttpURLConnection is the best choice for Android version 2.3 and beyond. Its API is simple and small in size, making it ideal for Android projects. Compression and caching mechanisms can effectively reduce network access to traffic, in terms of speed and power saving also played a big role. The new application should be more inclined to use httpurlconnection, because in future work we will also spend more time on the optimization httpurlconnection.

This article transferred from: http://blog.csdn.net/guolin_blog/article/details/12452307

Reprint Please specify: Android Development Chinese station? is Android accessing the network, using HttpURLConnection or httpclient?






is Android accessing the network, using HttpURLConnection or httpclient?

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.