摘自http://android-developers.blogspot.com/2011/09/androids-http-clients.html
Android’s HTTP Clients
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 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:
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.
分享到:
相关推荐
在Android平台上,开发者通常会遇到如何集成WebSocket的需求,本资料将详细介绍两种常见的Android WebSocket连接方式。 第一种连接方式:使用WebSocket库 1. **OkHttp + OkHttp-WebSocket-Client** OkHttp是一个...
虽然不是直接的网络连接方式,Fresco和Glide是两种流行的图片加载库,它们都支持网络图片加载。Fresco特别优化了大图加载,避免内存溢出,而Glide则以其简单易用和全面的图片处理能力受到开发者喜爱。 在实际开发...
本文将深入解析蓝牙连接过程,并提供解决此类问题的两种方法。 一、蓝牙连接原理及流程 1. 开启蓝牙:在手机设置中打开蓝牙功能,系统会自动扫描周围可用的蓝牙设备。 2. 搜索设备:手机会列出附近发现的蓝牙设备...
常见的联网请求方式有两种:HttpURLConnection和HttpClient。下面将详细讲解这两种方法,以及它们如何处理POST和GET请求。 **HttpURLConnection** HttpURLConnection是Java标准库提供的类,自Android 2.3(API级别9...
首先,USB转串口(USB to UART)是通过USB接口将数据转换成串行通信协议(如RS-232)的一种方式,广泛用于设备间的通信。Android系统支持USB主机模式(Host Mode),允许设备直接连接到USB设备,如Arduino、ESP8266...
连接WiFi通常有两种方式:一种是通过SSID和预设的密码直接连接,另一种是通过WiFi配置项(WifiConfiguration)。如果是已知的WiFi网络,可以通过以下方式连接: ```java WifiConfiguration wifiConfig = new ...
- BLE设备分为两种角色:中央设备(Central)和外围设备(Peripheral)。Android手机通常作为中央设备,搜索并连接外围设备。 2. **Android中的BLE API** - Android SDK提供了`BluetoothManager`类用于管理蓝牙...
Android支持多种蓝牙Profile,其中与蓝牙耳机相关的主要是`Headset`和`Handsfree`两种Profile。这些Profile定义了蓝牙设备之间通信的具体方式和服务类型。`BluetoothHeadsetService` 在接收到特定的动作后,会根据...
本教程将介绍两种方法来连接Unity3D项目到MySQL数据库。 首先,我们来看第一种方法,使用MySQLDriverCS库。MySQLDriverCS是一个专门用于C#(Unity3D支持的语言)连接MySQL数据库的库。要实现这一连接,首先需要下载...
无论选择哪种方式,都需要考虑网络权限(如`<uses-permission android:name="android.permission.INTERNET" />`)、错误处理和安全问题,例如防止网络数据泄露、处理网络不可用等情况。 总之,Android平台的网络...
- 蓝牙SPP和BLE模式的转换涉及到不同类型的BluetoothDevice和连接方式,需要正确处理不同协议下的连接状态和数据传输逻辑。 - 转换过程中,可能需要断开现有连接,重新初始化蓝牙适配器,并根据目标模式创建新的...
在Android应用开发中,客户端和服务端的连接是实现数据交互的关键环节。这个小型的网络服务器与安卓客户端的连接示例可能涵盖了HTTP、HTTPS协议、WebSocket、Socket编程等基础概念。以下将详细介绍这些知识点: 1. ...
本资源"android 很牛的蓝牙连接,ble,spp,欢迎下载学习"显然聚焦于这两种蓝牙协议在Android应用开发中的实践。下面我们将深入探讨蓝牙连接的基本概念、工作原理以及如何在Android上实现BLE和SPP(Serial Port ...
本篇文章将深入探讨两种启动Android服务的方式:startService和bindService,以及IntentService类的使用。 **1. startService()** `startService()` 是我们最常用来启动服务的方法。当你调用这个方法时,Android...
本文将深入探讨两种主要的网络监听实现方式:BroadcastReceiver和Socket编程。 首先,我们来了解BroadcastReceiver。BroadcastReceiver是Android系统中的一种组件,它可以监听并响应系统广播事件,包括网络连接状态...
在Android系统中,实现自动连接已配置好的Wi-Fi网络是一项常用的功能,特别是在设备启动或进入特定范围时。本文将深入探讨这一主题,基于提供的标题、描述以及相关标签,讲解如何在Android应用中实现这一功能。 ...
Socket是网络编程中的一个概念,它为应用程序提供了一种在两台机器间建立网络连接并进行数据交换的方法。在Android客户端与Java服务端之间建立长连接,意味着连接一旦建立,除非主动断开或因网络问题中断,否则将...
本文将深入探讨两种主要的获取位置信息的方法:GPS(全球定位系统)和网络定位,着重解决在无网络连接时如何利用GPS进行定位。 一、GPS定位 1. GPS简介: GPS是全球定位系统,通过接收多个卫星信号来确定设备的...
不论是哪种方式,为了防止阻塞主线程,Android应用通常会采用异步处理网络请求。你可以使用AsyncTask、Handler/Looper、Retrofit或使用Java 8的CompletableFuture等工具来实现异步操作。 在数据交换格式方面,通常...
本文将详细介绍如何使用`HttpClient`和`HttpsURLConnection`两种方式来访问HTTPS网站,包括验证证书和不验证证书的实现方法。 ### 1. Android中的HttpClient `HttpClient`是Apache提供的一种HTTP客户端库,它支持...