转载自:http://android-developers.blogspot.com/2011/09/androids-http-clients.html

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 couldpoison the connection pool. Work around this by disabling connection pooling:

privatevoid 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 a304 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 HTTP response caching on devices that support it. This sample code will turn on the response cache on Ice Cream Sandwich without affecting earlier releases:

privatevoid enableHttpResponseCache(){
    try{
        long httpCacheSize =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 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.

(转)Android’s HTTP Clients的更多相关文章

  1. Android’s HTTP Clients (httpClient 和 httpURLConnect 区别)

    来源自:http://android-developers.blogspot.jp/2011/09/androids-http-clients.html Most network-connected ...

  2. [Android]Volley源码分析(四)

    上篇中有提到NetworkDispatcher是通过mNetwork(Network类型)来进行网络访问的,现在来看一下关于Network是如何进行网络访问的. Network部分的类图:

  3. Android开源框架——Volley

    Volley 是 Google 在 2013 I/O 大会上推出的 Android 异步网络请求框架和图片加载框架.特别适合数据量小,通信频繁的网络操作.Volley 主要是通过两种 Diapatch ...

  4. [Android Pro] 关于Android的HTTP客户端的小秘密

    原文:http://android-developers.blogspot.com/2011/09/androids-http-clients.html 译文:http://yunfeng.sinaa ...

  5. Android网络连接的两种方法:apache client和httpurlconnection的比较

    另见http://blog.csdn.net/mingli198611/article/details/8766585 在官方blog中,android工程师谈到了如何去选择apache client ...

  6. android——网络操作(一)连接网络

    连接网络 一,包含许可 <uses-permissionandroid:name="android.permission.INTERNET"/> <uses-pe ...

  7. 【Android Developers Training】 79. 连接到网络

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  8. 聊聊HTTP gzip压缩与常见的Android网络框架

    版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/5835990.html 进入主题之前,我们先来看一下客户端与服 ...

  9. Android开发训练之第五章第七节——Transmitting Network Data Using Volley

    Transmitting Network Data Using Volley GET STARTED DEPENDENCIES AND PREREQUISITES Android 1.6 (API L ...

随机推荐

  1. tstring

      是的,一旦知道 TCHAR 和_T 是如何工作的,那么这个问题很简单.基本思想是 TCHAR 要么是char,要么是 wchar_t,这取决于 _UNICODE 的值: // abridged f ...

  2. ASP.NET MVC3.0或4.0设置二级域名的方法

    之前我就想做二级域名指向同一个IP同一个程序无非是在路由匹配规则上做文章也就是对Url的重写的一种思路.我用了半天时间上网查阅了相关资料并做了Demo测试是完全 以的,在这分享给大家... 假如网站主 ...

  3. centos静默式安装Oracle11g

    1.   Centos及Oracle版本 Centos:CentOS release 6.4 (Final) Oracle:linux.x64_Oracle_11gR2_database 2.   硬 ...

  4. ionic开发ios app

    注意必须是mac系统 1. 首先要安装node环境,Ionic的安装和后续的许多前端工具的安装都依赖于node的包管理器npm. nodeJs环境的安装很简单,去官网下载最新版的NodeJs直接安装即 ...

  5. hdu 1711 Number Sequence(KMP模板题)

    我的第一道KMP. 把两个数列分别当成KMP算法中的模式串和目标串,这道题就变成了一个KMP算法模板题. #include<stdio.h> #include<string.h> ...

  6. C++ Primer 5th 第1章 开始

    *****代码在Ubuntu g++ 5.31 / clang++ 3.8(C++11)下编写调试***** 每个C++程序必须有一个main( )函数,main( )函数的返回值也必须是int类型, ...

  7. android环境搭配 运行android sdk manager时出现错误问题解决

    本来前几天已经搭配好android环境开发(eclipse+android sdk+jdk),也已经运行成功了.但是最近因为出现了一些问题,所以把前面搭配好的环境都卸载了.重新搭配的时候发现在运行 s ...

  8. php基础之一

    php基础:1.php语言标记:<?php ?>2.输出语句:echo 'Hello','Hi'; //可输出多个字符串                 print 'World'; // ...

  9. win7下的iis配置

    1.配置错误 说明:在处理向该请求提供服务所需的配置文件时出错.请检查下面的特定错误详细信息并适当地修改配置文件. 分析器错误消息:无法识别的属性“targetFramework”.请注意属性名称区分 ...

  10. canvas加载图像

    之前按照例子,加载图像,发现加载图像,加载不上去,代码也没有错误,经过几次的尝试:发现需要重复调用下drawImage才可以. <script type="text/javascrip ...