Android 浅析 HttpURLConnection

前言

Linus Benedict Torvalds : RTFSC – Read The Funning Source Code

概述

HttpURLConnection是一种多用途、轻量极的HTTP客户端,使用它来进行HTTP操作可以适用于大多数的应用程序。

HttpURLConnection相对于HttpClient的优点:

HttpURLConnection HttpClient
Android SDK的标准实现 apache的开源实现
支持GZIP压缩 也支持,但要自己写代码处理
支持系统级连接池,即打开的连接不会直接关闭,在一段时间内所有程序可共用 不如官方直接系统底层支持好
在系统层面做了缓存策略处理,加快重复请求的速度

使用

使用这个类应该跟从以下步骤:

Step 1

Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection. 获得一个新的HttpURLConnection类应该调用URL.openConnection()并且将结果强转成HttpURLConnection类。

Step 2

Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.准备一个request。这个request主要属性是它的URI。Request的头部将会包含一些元数据例如凭证,首选内容类型和会话Cookie。

Step 3

Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by getOutputStream().可选上传的request内容。如果它包含一个request内容,实例必须配置为setDoOutput(true)。通过写入getOutputStream()返回的流来传输数据。

Step 4

Read the response. Response headers typically include metadata such as the response body’s content type and length, modified dates and session cookies. The response body may be read from the stream returned by getInputStream(). If the response has no body, that method returns an empty stream.读取响应。响应标头通常包括元数据,例如响应正文的内容类型和长度,修改日期和会话Cookie。 响应主体可以从getInputStream()返回的流中读取。 如果响应没有正文,那么该方法将返回一个空流。

Step 5

Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.断开链接。一旦响应内容被读取,HttpURLConnection应该要被关闭用disconnect()函数。断开连接释放连接持有的资源,以便它们可以被关闭或重用。

例子

1
2
3
4
5
6
7
8
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}

返回值

类型 键值
HTTP_ACCEPTED HTTP Status-Code 202: Accepted.
HTTP_BAD_GATEWAY HTTP Status-Code 502: Bad Gateway.
HTTP_BAD_METHOD HTTP Status-Code 405: Method Not Allowed.
HTTP_BAD_REQUEST HTTP Status-Code 400: Bad Request.
HTTP_CLIENT_TIMEOUT HTTP Status-Code 408: Request Time-Out.
HTTP_CONFLICT HTTP Status-Code 409: Conflict.
HTTP_CREATED HTTP Status-Code 201: Created.
HTTP_ENTITY_TOO_LARGE HTTP Status-Code 413: Request Entity Too Large.
HTTP_FORBIDDEN HTTP Status-Code 403: Forbidden.
HTTP_GATEWAY_TIMEOUT HTTP Status-Code 504: Gateway Timeout.
HTTP_GONE HTTP Status-Code 410: Gone.
HTTP_INTERNAL_ERROR HTTP Status-Code 500: Internal Server Error.
HTTP_LENGTH_REQUIRED HTTP Status-Code 411: Length Required.
HTTP_MOVED_PERM HTTP Status-Code 301: Moved Permanently.
HTTP_MOVED_TEMP HTTP Status-Code 302: Temporary Redirect.
HTTP_MULT_CHOICE HTTP Status-Code 300: Multiple Choices.
HTTP_NOT_ACCEPTABLE HTTP Status-Code 406: Not Acceptable.
HTTP_NOT_AUTHORITATIVE HTTP Status-Code 203: Non-Authoritative Information.
HTTP_NOT_FOUND HTTP Status-Code 404: Not Found.
HTTP_NOT_IMPLEMENTED HTTP Status-Code 501: Not Implemented.
HTTP_NOT_MODIFIED HTTP Status-Code 304: Not Modified.
HTTP_NO_CONTENT HTTP Status-Code 204: No Content.
HTTP_OK HTTP Status-Code 200: OK.
HTTP_PARTIAL HTTP Status-Code 206: Partial Content.
HTTP_PAYMENT_REQUIRED HTTP Status-Code 402: Payment Required.
HTTP_PRECON_FAILED HTTP Status-Code 412: Precondition Failed.
HTTP_PROXY_AUTH HTTP Status-Code 407: Proxy Authentication Required.
HTTP_REQ_TOO_LONG HTTP Status-Code 414: Request-URI Too Large.
HTTP_RESET HTTP Status-Code 205: Reset Content.
HTTP_SEE_OTHER HTTP Status-Code 303: See Other.
HTTP_SERVER_ERROR This constant was deprecated in API level 1. it is misplaced and shouldn’t have existed.
HTTP_UNAUTHORIZED HTTP Status-Code 401: Unauthorized.
HTTP_UNAVAILABLE HTTP Status-Code 503: Service Unavailable.
HTTP_UNSUPPORTED_TYPE HTTP Status-Code 415: Unsupported Media Type.
HTTP_USE_PROXY HTTP Status-Code 305: Use Proxy.
HTTP_VERSION HTTP Status-Code 505: HTTP Version Not Supported.

针对链接的属性一些定义:
通用首部字段
请求首部字段
响应首部字段
实体首部字段

详细使用

Get操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
private void requestGet(HashMap<String, String> paramsMap) {
try {
String baseUrl = "https://baidu.com/";
StringBuilder tempParams = new StringBuilder();
int pos = 0;
for (String key : paramsMap.keySet()) {
if (pos > 0) {
tempParams.append("&");
}
tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key),"utf-8")));
pos++;
}
String requestUrl = baseUrl + tempParams.toString();
// 新建一个URL对象
URL url = new URL(requestUrl);
// 打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置连接主机超时时间
urlConn.setConnectTimeout(5 * 1000);
// 设置从主机读取数据超时
urlConn.setReadTimeout(5 * 1000);
// 设置是否使用缓存 默认是true
urlConn.setUseCaches(true);
// 设置为Post请求
urlConn.setRequestMethod("GET");
// urlConn设置请求头信息
// 设置请求中的媒体类型信息。
urlConn.setRequestProperty("Content-Type", "application/json");
// 设置客户端与服务连接类型
urlConn.addRequestProperty("Connection", "Keep-Alive");
// 开始连接
urlConn.connect();
// 判断请求是否成功
if (urlConn.getResponseCode() == 200) {
// 获取返回的数据
String result = streamToString(urlConn.getInputStream());
Log.e(TAG, "Get方式请求成功,result--->" + result);
} else {
Log.e(TAG, "Get方式请求失败");
}
// 关闭连接
urlConn.disconnect();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}

Post操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
private void requestPost(HashMap<String, String> paramsMap) {
try {
String baseUrl = "https://baidu.com/";
// 合成参数
StringBuilder tempParams = new StringBuilder();
int pos = 0;
for (String key : paramsMap.keySet()) {
if (pos > 0) {
tempParams.append("&");
}
tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key),"utf-8")));
pos++;
}
String params =tempParams.toString();
// 请求的参数转换为byte数组
byte[] postData = params.getBytes();
// 新建一个URL对象
URL url = new URL(baseUrl);
// 打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(5 * 1000);
// 设置从主机读取数据超时
urlConn.setReadTimeout(5 * 1000);
// Post请求必须设置允许输出 默认false
urlConn.setDoOutput(true);
// 设置请求允许输入 默认是true
urlConn.setDoInput(true);
// Post请求不能使用缓存
urlConn.setUseCaches(false);
// 设置为Post请求
urlConn.setRequestMethod("POST");
// 设置本次连接是否自动处理重定向
urlConn.setInstanceFollowRedirects(true);
// 配置请求Content-Type
urlConn.setRequestProperty("Content-Type", "application/json");
// 开始连接
urlConn.connect();
// 发送请求参数
DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
dos.write(postData);
dos.flush();
dos.close();
// 判断请求是否成功
if (urlConn.getResponseCode() == 200) {
// 获取返回的数据
String result = streamToString(urlConn.getInputStream());
Log.e(TAG, "Post方式请求成功,result--->" + result);
} else {
Log.e(TAG, "Post方式请求失败");
}
// 关闭连接
urlConn.disconnect();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}

download操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
private void downloadFile(String fileUrl){
try {
// 新建一个URL对象
URL url = new URL(fileUrl);
// 打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置连接主机超时时间
urlConn.setConnectTimeout(5 * 1000);
// 设置从主机读取数据超时
urlConn.setReadTimeout(5 * 1000);
// 设置是否使用缓存 默认是true
urlConn.setUseCaches(true);
// 设置为Post请求
urlConn.setRequestMethod("GET");
// urlConn设置请求头信息
// 设置请求中的媒体类型信息。
urlConn.setRequestProperty("Content-Type", "application/json");
// 设置客户端与服务连接类型
urlConn.addRequestProperty("Connection", "Keep-Alive");
// 开始连接
urlConn.connect();
// 判断请求是否成功
if (urlConn.getResponseCode() == 200) {
String filePath="";
File descFile = new File(filePath);
FileOutputStream fos = new FileOutputStream(descFile);;
byte[] buffer = new byte[1024];
int len;
InputStream inputStream = urlConn.getInputStream();
while ((len = inputStream.read(buffer)) != -1) {
// 写到本地
fos.write(buffer, 0, len);
}
} else {
Log.e(TAG, "文件下载失败");
}
// 关闭连接
urlConn.disconnect();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}

上传操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
private void upLoadFile(String filePath, HashMap<String, String> paramsMap) {
try {
String baseUrl = "https://baidu.com/uploadFile";
File file = new File(filePath);
// 新建url对象
URL url = new URL(baseUrl);
// 通过HttpURLConnection对象,向网络地址发送请求
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置该连接允许读取
urlConn.setDoOutput(true);
// 设置该连接允许写入
urlConn.setDoInput(true);
// 设置不能适用缓存
urlConn.setUseCaches(false);
// 设置连接超时时间
urlConn.setConnectTimeout(5 * 1000); // 设置连接超时时间
// 设置读取超时时间
urlConn.setReadTimeout(5 * 1000); // 读取超时
// 设置连接方法post
urlConn.setRequestMethod("POST");
// 设置维持长连接
urlConn.setRequestProperty("connection", "Keep-Alive");
// 设置文件字符集
urlConn.setRequestProperty("Accept-Charset", "UTF-8");
// 设置文件类型
urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "*****");
String name = file.getName();
DataOutputStream requestStream = new DataOutputStream(urlConn.getOutputStream());
requestStream.writeBytes("--" + "*****" + "\r\n");
// 发送文件参数信息
StringBuilder tempParams = new StringBuilder();
tempParams.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + name + "\"; ");
int pos = 0;
int size = paramsMap.size();
for (String key : paramsMap.keySet()) {
tempParams.append( String.format("%s=\"%s\"", key, paramsMap.get(key), "utf-8"));
if (pos < size-1) {
tempParams.append("; ");
}
pos++;
}
tempParams.append("\r\n");
tempParams.append("Content-Type: application/octet-stream\r\n");
tempParams.append("\r\n");
String params = tempParams.toString();
requestStream.writeBytes(params);
//发送文件数据
FileInputStream fileInput = new FileInputStream(file);
int bytesRead;
byte[] buffer = new byte[1024];
DataInputStream in = new DataInputStream(new FileInputStream(file));
while ((bytesRead = in.read(buffer)) != -1) {
requestStream.write(buffer, 0, bytesRead);
}
requestStream.writeBytes("\r\n");
requestStream.flush();
requestStream.writeBytes("--" + "*****" + "--" + "\r\n");
requestStream.flush();
fileInput.close();
int statusCode = urlConn.getResponseCode();
if (statusCode == 200) {
// 获取返回的数据
String result = streamToString(urlConn.getInputStream());
Log.e(TAG, "上传成功,result--->" + result);
} else {
Log.e(TAG, "上传失败");
}
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}

Request部分

Header 解释 示例
Accept 指定客户端能够接收的内容类型 Accept: text/plain, text/html
Accept-Charset 浏览器可以接受的字符编码集。 Accept-Charset: iso-8859-5
Accept-Encoding 指定浏览器可以支持的web服务器返回内容压缩编码类型。 Accept-Encoding: compress, gzip
Accept-Language 浏览器可接受的语言 Accept-Language: en,zh
Accept-Ranges 可以请求网页实体的一个或者多个子范围字段 Accept-Ranges: bytes
Authorization HTTP授权的授权证书 Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Cache-Control 指定请求和响应遵循的缓存机制 Cache-Control: no-cache
Connection 表示是否需要持久连接。(HTTP 1.1默认进行持久连接) Connection: close
Cookie HTTP请求发送时,会把保存在该请求域名下的所有cookie值一起发送给web服务器。 Cookie: $Version=1; Skin=new;
Content-Length 请求的内容长度 Content-Length: 348
Content-Type 请求的与实体对应的MIME信息 Content-Type: application/x-www-form-urlencoded
Date 请求发送的日期和时间 Date: Tue, 15 Nov 2010 08:12:31 GMT
Expect 请求的特定的服务器行为 Expect: 100-continue
From 发出请求的用户的Email From: user@email.com
Host 指定请求的服务器的域名和端口号 Host:
If-Match 只有请求内容与实体相匹配才有效 If-Match: “737060cd8c284d8af7ad3082f209582d”
If-Modified-Since 如果请求的部分在指定时间之后被修改则请求成功,未被修改则返回304代码 If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT
If-None-Match 如果内容未改变返回304代码,参数为服务器先前发送的Etag,与服务器回应的Etag比较判断是否改变 If-None-Match: “737060cd8c284d8af7ad3082f209582d”
If-Range 如果实体未改变,服务器发送客户端丢失的部分,否则发送整个实体。参数也为Etag If-Range: “737060cd8c284d8af7ad3082f209582d”
If-Unmodified-Since 只在实体在指定时间之后未被修改才请求成功 If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT
Max-Forwards 限制信息通过代理和网关传送的时间 Max-Forwards: 10
Pragma 用来包含实现特定的指令 Pragma: no-cache
Proxy-Authorization 连接到代理的授权证书 Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Range 只请求实体的一部分,指定范围 Range: bytes=500-999
Referer 先前网页的地址,当前请求网页紧随其后,即来路 Referer: 告诉服务器我是从哪个页面链接过来的
TE 客户端愿意接受的传输编码,并通知服务器接受接受尾加头信息 TE: trailers,deflate;q=0.5
Upgrade 向服务器指定某种传输协议以便服务器进行转换(如果支持) Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11
User-Agent User-Agent的内容包含发出请求的用户信息 User-Agent: Mozilla/5.0 (Linux; X11)
Via 通知中间网关或代理服务器地址,通信协议 Via: 1.0 fred, 1.1 nowhere.com

Responses 部分

Header 解释 示例
Accept-Ranges 表明服务器是否支持指定范围请求及哪种类型的分段请求 Accept-Ranges: bytes
Age 从原始服务器到代理缓存形成的估算时间(以秒计,非负) Age: 12
Allow 对某网络资源的有效的请求行为,不允许则返回405 Allow: GET, HEAD
Cache-Control 告诉所有的缓存机制是否可以缓存及哪种类型 Cache-Control: no-cache
Content-Encoding web服务器支持的返回内容压缩编码类型。 Content-Encoding: gzip
Content-Language 响应体的语言 Content-Language: en,zh
Content-Length 响应体的长度 Content-Length: 348
Content-Location 请求资源可替代的备用的另一地址 Content-Location: /index.htm
Content-MD5 返回资源的MD5校验值 Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==
Content-Range 在整个返回体中本部分的字节位置 Content-Range: bytes 21010-47021/47022
Content-Type 返回内容的MIME类型 Content-Type: text/html; charset=utf-8
Date 原始服务器消息发出的时间 Date: Tue, 15 Nov 2010 08:12:31 GMT
ETag 请求变量的实体标签的当前值 ETag: “737060cd8c284d8af7ad3082f209582d”
Expires 响应过期的日期和时间 Expires: Thu, 01 Dec 2010 16:00:00 GMT
Last-Modified 请求资源的最后修改时间 Last-Modified: Tue, 15 Nov 2010 12:45:26 GMT
Location 用来重定向接收方到非请求URL的位置来完成请求或标识新的资源 Location: http://www.zcmhi.com/archives/94.html
Pragma 包括实现特定的指令,它可应用到响应链上的任何接收方 Pragma: no-cache
Proxy-Authenticate 它指出认证方案和可应用到代理的该URL上的参数 Proxy-Authenticate: Basic
refresh 应用于重定向或一个新的资源被创造,在5秒之后重定向(由网景提出,被大部分浏览器支持) Refresh: 5; url=http://www.zcmhi.com/archives/94.html
Retry-After 如果实体暂时不可取,通知客户端在指定时间之后再次尝试 Retry-After: 120
Server web服务器软件名称 Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
Set-Cookie 设置Http Cookie Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1
Trailer 指出头域在分块传输编码的尾部存在 Trailer: Max-Forwards
Transfer-Encoding 文件传输编码 Transfer-Encoding:chunked
Vary 告诉下游代理是使用缓存响应还是从原始服务器请求 Vary: *
Via 告知代理客户端响应是通过哪里发送的 Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning 警告实体可能存在的问题 Warning: 199 Miscellaneous warning
WWW-Authenticate 表明客户端请求实体应该使用的授权方案 WWW-Authenticate: Basic

注意点

  1. HttpURLConnection的connect()函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。 无论是post还是get,http请求实际上直到HttpURLConnection的getInputStream()这个函数里面才正式发送出去。
  2. 在用POST方式发送URL请求时,URL请求参数的设定顺序是重中之重,对connection对象的一切配置(那一堆set函数) 都必须要在connect()函数执行之前完成。而对outputStream的写操作,又必须要在inputStream的读操作之前。这些顺序实际上是由http请求的格式决定的。
  3. http请求实际上由两部分组成,一个是http头,所有关于此次http请求的配置都在http头里面定义, 一个是正文content。connect()函数会根据HttpURLConnection对象的配置值生成http头部信息,因此在调用connect函数之前,就必须把所有的配置准备好。
  4. 在http头后面紧跟着的是http请求的正文,正文的内容是通过outputStream流写入的,实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络, 而是存在于内存缓冲区中,待outputStream流关闭时,根据输入的内容生成http正文。至此,http请求的东西已经全部准备就绪。在getInputStream()函数调用的时候,就会把准备好的http请求 正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http请求的返回信息。由于http 请求在getInputStream的时候已经发送出去了(包括http头和正文),因此在getInputStream()函数 之后对connection对象进行设置(对http头的信息进行修改)或者写入outputStream(对正文进行修改)都是没有意义的了,执行这些操作会导致异常的发生。