Android-浅析-HttpURLConnection

原文:https://jasonzhong.github.io/2017/01/26/Android-%E6%B5%85%E6%9E%90-HttpURLConnection/

前言

Linus Benedict Torvalds : RTFSC – Read The Funning Source Code

概述

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

HttpURLConnection相对于HttpClient的优点:

HttpURLConnectionHttpClient
Android SDK的标准实现apache的开源实现
支持GZIP压缩也支持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()函数。断开连接释放连接持有的资源,以便它们可以被关闭或重用。

例子

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_ACCEPTEDHTTP Status-Code 202: Accepted.
HTTP_BAD_GATEWAYHTTP Status-Code 502: Bad Gateway.
HTTP_BAD_METHODHTTP Status-Code 405: Method Not Allowed.
HTTP_BAD_REQUESTHTTP Status-Code 400: Bad Request.
HTTP_CLIENT_TIMEOUTHTTP Status-Code 408: Request Time-Out.
HTTP_CONFLICTHTTP Status-Code 409: Conflict.
HTTP_CREATEDHTTP Status-Code 201: Created.
HTTP_ENTITY_TOO_LARGEHTTP Status-Code 413: Request Entity Too Large.
HTTP_FORBIDDENHTTP Status-Code 403: Forbidden.
HTTP_GATEWAY_TIMEOUTHTTP Status-Code 504: Gateway Timeout.
HTTP_GONEHTTP Status-Code 410: Gone.
HTTP_INTERNAL_ERRORHTTP Status-Code 500: Internal Server Error.
HTTP_LENGTH_REQUIREDHTTP Status-Code 411: Length Required.
HTTP_MOVED_PERMHTTP Status-Code 301: Moved Permanently.
HTTP_MOVED_TEMPHTTP Status-Code 302: Temporary Redirect.
HTTP_MULT_CHOICEHTTP Status-Code 300: Multiple Choices.
HTTP_NOT_ACCEPTABLEHTTP Status-Code 406: Not Acceptable.
HTTP_NOT_AUTHORITATIVEHTTP Status-Code 203: Non-Authoritative Information.
HTTP_NOT_FOUNDHTTP Status-Code 404: Not Found.
HTTP_NOT_IMPLEMENTEDHTTP Status-Code 501: Not Implemented.
HTTP_NOT_MODIFIEDHTTP Status-Code 304: Not Modified.
HTTP_NO_CONTENTHTTP Status-Code 204: No Content.
HTTP_OKHTTP Status-Code 200: OK.
HTTP_PARTIALHTTP Status-Code 206: Partial Content.
HTTP_PAYMENT_REQUIREDHTTP Status-Code 402: Payment Required.
HTTP_PRECON_FAILEDHTTP Status-Code 412: Precondition Failed.
HTTP_PROXY_AUTHHTTP Status-Code 407: Proxy Authentication Required.
HTTP_REQ_TOO_LONGHTTP Status-Code 414: Request-URI Too Large.
HTTP_RESETHTTP Status-Code 205: Reset Content.
HTTP_SEE_OTHERHTTP Status-Code 303: See Other.
HTTP_SERVER_ERRORThis constant was deprecated in API level 1. it is misplaced and shouldn't have existed.
HTTP_UNAUTHORIZEDHTTP Status-Code 401: Unauthorized.
HTTP_UNAVAILABLEHTTP Status-Code 503: Service Unavailable.
HTTP_UNSUPPORTED_TYPEHTTP Status-Code 415: Unsupported Media Type.
HTTP_USE_PROXYHTTP Status-Code 305: Use Proxy.
HTTP_VERSIONHTTP Status-Code 505: HTTP Version Not Supported.

针对链接的属性一些定义:

详细使用

Get操作

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操作

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操作

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

上传操作

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
AuthorizationHTTP授权的授权证书Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Cache-Control指定请求和响应遵循的缓存机制Cache-Control: no-cache
Connection表示是否需要持久连接。(HTTP 1.1默认进行持久连接)Connection: close
CookieHTTP请求发送时,会把保存在该请求域名下的所有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发出请求的用户的EmailFrom: user@email.com
Host指定请求的服务器的域名和端口号Host: www.zcmhi.com
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如果实体未改变,服务器发送客户端丢失的部分,否则发送整个实体。参数也为EtagIf-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: http://www.zcmhi.com/archives/71.html
TE客户端愿意接受的传输编码,并通知服务器接受接受尾加头信息TE: trailers,deflate;q=0.5
Upgrade向服务器指定某种传输协议以便服务器进行转换(如果支持)Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11
User-AgentUser-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对某网络资源的有效的请求行为,不允许则返回405Allow: GET, HEAD
Cache-Control告诉所有的缓存机制是否可以缓存及哪种类型Cache-Control: no-cache
Content-Encodingweb服务器支持的返回内容压缩编码类型。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
Serverweb服务器软件名称Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
Set-Cookie设置Http CookieSet-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(对正文进行修改)都是没有意义的了,执行这些操作会导致异常的发生。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值