现在的位置: 首页 > 移动开发> 正文
探讨 Android 网络编程
2011年09月30日 移动开发 暂无评论 ⁄ 被围观 6,202+

前言

谈到 Android 的网络编程,相信大家都不会陌生,我们平时用到的也就是两种 Http Client,分别为 HttpURLConnection 和  Apache HTTP Client,下面就分析一下它们各自的适用场合。

Most network-connected Android apps will use HTTP to send and receive data. Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.

Apache HTTP Client

Apache Http Client 的优势是适合于作为web 浏览器的客户端和稳定性较好,并且可灵活配置,缺点是在追求兼容性的情况下难以扩展。

DefaultHttpClient and its sibling AndroidHttpClient are extensible HTTP clients suitable for web browsers. They have large and flexible APIs. Their implementation is stable and they have few bugs.

But the large size of this API makes it difficult for us to improve it without breaking compatibility. The Android team is not actively working on Apache HTTP Client.

HttpURLConnection

HttpURLConnection的优势是作为一个轻量级的 Http Client,适合于大多数的应用程序,可扩展性较好,缺点是健壮性不够好。

HttpURLConnection is a general-purpose, lightweight HTTP client suitable for most applications. This class has humble beginnings, but its focused API has made it easy for us to improve steadily.

Prior to Froyo, HttpURLConnection had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:

private void disableConnectionReuseIfNecessary() {    
      // HTTP connection reuse which was buggy pre-froyo    
      if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {        
          System.setProperty("http.keepAlive", "false");    
      }
}

开启透明压缩,减少和服务器端的数据交互。

In Gingerbread, we added transparent response compression. HttpURLConnection will automatically add this header to outgoing requests, and handle the corresponding response:

Accept-Encoding: gzip

Take advantage of this by configuring your Web server to compress responses for clients that can support it. If response compression is problematic, theclass documentation shows how to disable it.

Since HTTP’s Content-Length header returns the compressed size, it is an error to use getContentLength() to size buffers for the uncompressed data. Instead, read bytes from the response until InputStream.read() returns -1.

We also made several improvements to HTTPS in Gingerbread. HttpsURLConnection attempts to connect with Server Name Indication (SNI) which allows multiple HTTPS hosts to share an IP address. It also enables compression and session tickets. Should the connection fail, it is automatically retried without these features. This makes HttpsURLConnection efficient when connecting to up-to-date servers, without breaking compatibility with older ones.

In Ice Cream Sandwich, we are adding a response cache. With the cache installed, HTTP requests will be satisfied in one of three ways:

  • Fully cached responses are served directly from local storage. Because no network connection needs to be made such responses are available immediately.
  • Conditionally cached responses must have their freshness validated by the webserver. The client sends a request like “Give me /foo.png if it changed since yesterday” and the server replies with either the updated content or a 304 Not Modified status. If the content is unchanged it will not be downloaded!
  • Uncached responses are served from the web. These responses will get stored in the response cache for later.

利用反射机制开启Https的缓冲机制。

Use reflection to enable HTTPS response caching on devices that support it. This sample code will turn on the response cache on Ice Cream Sandwich without affecting earlier releases:

private void enableHttpResponseCache() {    
  try {        
      long httpCacheSize = 10 * 1024 * 1024; // 10 MiB        
      File httpCacheDir = new File(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 set cache headers on its HTTP responses.

Which client is best?

Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.

通过上面的了解,发现Google官方还是特别推荐利用Android原生态的HttpURLConnection,在Android较早的版本中适合Apache的Http Client,主要是稳定性比较好,在以后的Android版本中适合用HttpURLConnection,相信随着Android系统的不断升级,功能会越来越完善,透明压缩和数据缓存可以有效减少客户端和服务器的数据交互,降低网络流量,提高浏览速度。

For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward.

原文链接:Android’s HTTP Clients

给我留言

留言无头像?


×
腾讯微博