`
ericbaner
  • 浏览: 177434 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Android HTTP Clients使用选择介绍

 
阅读更多

翻译稿:

 

大多数需要网络连接的Android应用会使用HTTP协议发送和接收数据。Android包含两种Http客户端类, HttpURLConnection和Apache的HttpClient。这两者都支持HTTPS,streaming 上传与下载,配置超时时间,IPv6, 以及连接池。

 

Apache Http Client

 

DefaultHttpClient 和它的兄弟类AndroidHttpClient是可扩展的Http客户端,适用于Web浏览器。它们有大量的灵活的API,其实现是稳定的,极少有bug. 但是, 其巨大的API数量导致我们难以改进它们而不破坏兼容性。 Android团队现在已不活跃于在Apache HttpClient上的工作了。

 

HttpURLConnection

 

HttpURLConnection是一个适用于多数应用的通用的,轻量级的Http客户端。该类起初较粗糙,但其关注的API让我们容易稳固地改进它。 在Froyo(2.2)之前,HttpURLConnection有一些令人沮丧的的bug。特别是,在一个可读的InputStream上调用close()可阻碍连接池。绕过这个bug只能关掉连接池。

 

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");
    }
}

 

在Gingerbread(2.3),我们增加了透明的应答压缩。HttpURLConnection将自动地将“Accept-Encoding: gzip” 头字段添加进上行的请求,并处理相应的应答。 通过配置你的Web服务器,对支持的客户端返回压缩后的应用数据。如果应用压缩是有问题的,可参见类文档如何关掉它。

 

因为HTTP的Content-Length头字段返回的是压缩后的大小, 使用getContentLength()来分配解压缩后数据的buffer 大小是错误的。 应该从应答中读字节直到InputStream.read()返回-1。

 

我们还在Gingerbread上对HTTPS作出了一些改进。HttpsURLConnection尝试以Server Name Indication(SNI)连接, SNI允许多个HTTPS host共享一个IP地址。HttpsURLConnection还具备压缩和会话ticket功能。没有这些功能,一旦连接失败,它会自动重试。这使得HttpsURLConnection有效地连接最新的服务器,同时不破坏对老旧服务器的兼容性。

 

在Ice Cream Sandwich(2.4 or 4.0),我们增加了应答cache。配备了cache后,HTTP 请求以以下三种方式之一处理:

 

1)全cache的应答将直接从本地存储中获取。因为不需要网络连接,此类应答可以立即获取到。

 

2)有条件cache的应答必须在Web服务器验证一下cache的有效性。客户端发送一个请求,比如

“Give me /foo.png if it changed  since yesterday” , 服务端的应答要么是更新后的内容,要么是304 没有修改状态码。如果内容是没有改变的,就不需要下载了。

 

3)没有cache的应答将从服务器上获取。这些应答之后将存储在应答cache中。

 

可以使用”反射“(reflection)机制来使Https 应答cache功能在支持的设备上运行。以下示例代码将会在Ice Cream Sandwich上打开应答cache功能而不影响到早期的版本:

 

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) {
    }
}

 

当然,你也应该配置你的Web服务器,在其Http应答中设置cache头字段。

 

哪一个更好呢?

 

Apache HTTP client在Eclair(2.1)和Froyo(2.2)上bug更少,在这些系统版本上将是最佳选择。

 

在Gingerbread(2.3)系统及以后,HttpURLConnection将是最佳选择,其API简单,小巧,非常适合于Android。透明的压缩及应答cache机制减少了网络流量,改进了网络速度,节省了电力。 新的应用将应该使用HttpURLConnection, 它是Android团队以后花费精力不断推进的地方。

 

 

 

原文:

 

[This post is by Jesse Wilson from the Dalvik team. —Tim Bray]

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

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 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, the class 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.

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.

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.

0
0
分享到:
评论
3 楼 songfantasy 2012-01-11  
ericbaner 写道

被墙了吗?
1 楼 songfantasy 2012-01-05  
原文在哪儿搞的?楼主?

相关推荐

    Android代码-Rtsp-Android-Client

    [x] 支持H264硬解码显示(Android 4.1以上版本支持) [ ] 支持H264软解码显示 &gt; - [ ] 支持ACC音频 使用方法 使用Jcenter仓库 &gt; compile "com.aaronhan:rtspclient:0.7" 调用RtspClient方法 private ...

    http_client for android 工具包

    http_client for android 工具包

    android TCP server 和TCP client通信源码

    在Android上,我们可以使用Java的Socket类来实现这两部分。 对于Android TCP服务器,我们需要创建一个线程来监听特定的端口号。一旦有客户端连接,服务器会创建一个新的Socket对象来处理这个连接,并通过Socket的...

    Android Asynchronous Http Client的用法实例

    // 1.创建异步请求的客户端对象 ...其他有什么问题或者想具体了解详细说明,可以参考官网 http://loopj.com/android-async-http/ 其他参考链接 http://blog.csdn.net/redarmy_chen/article/details/26980613

    Android开发,Socket Client端和Socket Server端数据发送和接收

    本篇文章将详细探讨Android环境下如何进行Socket Client端和Socket Server端的数据发送与接收。 1. **Socket基础知识** - **Socket定义**:Socket是网络编程中的一个接口,它允许应用程序通过TCP/IP协议进行数据...

    Android TCP_Client

    在这个"Android TCP_Client"项目中,我们探讨了如何在Android设备上创建一个TCP客户端,以便与远程服务器进行数据交换。 首先,Android TCP客户端的核心在于使用Java的Socket类来建立与服务器的连接。Socket是网络...

    AndroidTCP Client and Server

    在Android中,我们可以使用`ServerSocket`类来创建服务器端点,并设置监听的端口号。 2. **客户端**:客户端则需要知道服务器的IP地址和端口号,然后创建一个`Socket`对象来发起连接请求。 3. **连接建立**:当...

    Android代码-DNS Client for Android

    androdns Android DNS Client Google Play: https://play.google.com/store/apps/details?id=androdns.android.leetdreams.ch.androdns

    Android TCP Client demo

    下面将详细介绍如何在Android 4.4.4及更高版本上构建一个TCP客户端示例。 1. **TCP基础知识**: - **TCP(Transmission Control Protocol)** 是一种面向连接的、可靠的、基于字节流的传输层通信协议。它通过三次...

    android socket client

    标题"android socket client"表明我们将讨论如何在Android设备上实现一个Socket客户端,用于接收服务器端发送的数据。描述中提到,通常看到的教程多是客户端向服务器发送数据,而这里我们关注的是服务器主动向客户端...

    secoclient-android-ios-7.0.2.26.zip

    对于Android用户,"secoclient-android-7.0.2.26.apk"是一个可安装的APK文件,它包含了SecoClient在Android平台上的所有代码和资源。APK是Android应用程序的标准格式,用户可以通过安装这个文件来获取SecoClient的...

    mqtt android client require jar

    标题和描述中提到的"mqtt android client require jar"表明我们正在寻找适用于Android的MQTT客户端所需的Java类库。 `mqtt-client-0.4.0.jar` 是一个基础的MQTT客户端库,它提供了与MQTT服务器进行交互的基本功能。...

    zxing-client-android

    "ZXing-client-android"是一个基于Android平台的二维码和条形码扫描与生成工具的源代码库。这个项目的核心是ZXing(发音为 "zebra crossing"),它是一个开放源代码的多格式一维和二维条码图像处理库,用于读取、...

    Android JAVACV RTMP Client

    综上所述,"Android JAVACV RTMP Client"项目涉及了Android音视频录制、JavaCV库的使用、RTMP协议的实现、RED5服务器的交互等多个技术领域,对于开发者来说,需要具备扎实的Android基础知识以及网络编程经验。

    android-http-client:适用于Android的简单轻便的HTTP客户端

    Android HTTP客户端 Android Http Client是一个小型库,用于以简单实用的方式向任何Internet服务发出请求。 您可以实现多个接口来管理响应。 它还包括用于管理文件上载和... JSON :Android Http Client使用获取兼容性

    secoclient-android-7.0.5.1.apk

    华为 secoclient 客户端 7.0.5.1 for android

    Android socket 学习记录 client端源码

    以上就是`Android socket 学习记录 client端源码`的主要内容,通过学习和实践这部分代码,你可以掌握如何在Android客户端使用Socket与服务器进行通信,为开发实时聊天、文件传输等应用打下坚实的基础。在实际开发中...

    IPClient for Android 201408版

    出校控制器IPClient的Android版,2014年8月,支持桂林电子科技大学及广西师范大学

    Android代码-LogDNA-Android-Client

    LogDNA-Android-Client Android client for LogDNA Add the JitPack repository to your build file allprojects { repositories { ... maven { url 'https://jitpack.io' } } } Add dependency dependencies ...

    Funambol Sync Client for Android

    Funambol Sync Client for Android is a client to synchronize PIM Data of Android devices with any SyncML aware server. For the moment, it is an experimental project to explore the possibility of the...

Global site tag (gtag.js) - Google Analytics