全部开发者教程

Android 入门教程

菜单类控件
菜单:Menu
并发编程
多线程

HTTP 使用详解

在你浏览互联网的时候,绝大多数的数据都是通过 HTTP 协议获取到的,也就是说如果你想要实现一个能上网的 App,那么就一定会和 HTTP 打上交道。当然 Android 发展到现在这么多年,已经有很多非常好用,功能非常完善的网络框架了,比如 Volley、OkHttp、retrofit等,但是底层逻辑都是一样的。本节我们来学习 Android 原声支持的 HTTP 接口,相比那些第三方框架,它的封装更好,也更适合我们了解底层原理。

1. Http 协议

Http 底层基于 TCP 协议,分为请求和响应。请求和响应分别有各自的 Header 和 Body 组成。Header 里面通常是本次请求 / 响应的描述信息,比如版本号、长度、UA、Content-Type 等等,而 Body 里面通常就是我们要传递的业务数据了,下面分别浏览一下请求和响应的内容。

1.1 Http 请求

请求头的内容有很多,这里给大家做一个记录当做资料,不需要都记住,在实际使用中用到可以过来查阅即可。

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 QWxhZIRpbjpvcGAuIHNlc2FtZQ==
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: https://www.imooc.com/wiki/androidlesson/
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 QWxhZGbpbjpAcGVuIHNlc2FtZQ==
Range 只请求实体的一部分,指定范围 Range: bytes=500-999
Referer 先前网页的地址,当前请求网页紧随其后,即来路 https://www.imooc.com/wiki/androidlesson/
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 (Apache/1.1)
Warning 关于消息实体的警告信息 Warn: 199 Miscellaneous warning

1.2 Http 响应

响应就是服务器收到我们的 request 之后给我们返回的数据,同样记录一下响应头:

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: https://www.imooc.com/wiki/androidlesson/
Pragma 包括实现特定的指令,它可应用到响应链上的任何接收方 Pragma: no-cache
Proxy-Authenticate 它指出认证方案和可应用到代理的该URL上的参数 Proxy-Authenticate: Basic

2. HttpUrlConnection 接口

Android 系统为我们提供了 HttpUrlConnection 接口用于实现 Http 请求。自从 Android API
9 开始,HttpUrlConnection 就成为了 Android App 推荐使用的内置 Http 库。使用它无需添加任何依赖,打开网络权限:

<uses-permission android:name="android.permission.INTERNET" />

就可以访问 Http 资源了,可以说相比第三方框架

3. HttpUrlConnection 的使用步骤

首先还是引用一下 Google 官方的使用文档:

A URLConnection with support for HTTP-specific features. See the spec for details.
Uses of this class follow a pattern:

  1. Obtain a new HttpURLConnection by calling [URL#openConnection()](https://developer.android.com/reference/java/net/URL#openConnection()) and casting the result to HttpURLConnection.
  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.
  3. Optionally upload a request body. Instances must be configured with [setDoOutput(true)](https://developer.android.com/reference/java/net/URLConnection#setDoOutput(boolean)) if they include a request body. Transmit data by writing to the stream returned by [URLConnection.getOutputStream()](https://developer.android.com/reference/java/net/URLConnection#getOutputStream()).
  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 [URLConnection.getInputStream()](https://developer.android.com/reference/java/net/URLConnection#getInputStream()). If the response has no body, that method returns an empty stream.
  5. Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling [disconnect()](https://developer.android.com/reference/java/net/HttpURLConnection#disconnect()). Disconnecting releases the resources held by a connection so they may be closed or reused.

官方文档没有对 Http 协议本身做什么解释(如果对 Http 协议不太了解的同学,可以参考慕课网上网络相关课程),主要是围绕 HttpUrlConnection 的用法展开了一步步的描述,结合官网的解释以及我个人的总结,大体上可以分为一下几步:

  1. 通过openConnection()方法创建一个HttpURLConnection
URL url = new URL(https://www.baidu.com);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

首先创建一个 URL 对象,参数就是我们要打开的地址,然后使用 url 对象的openConnection()来打开 Http 连接,拿到一个HttpURLConnection对象。
2. 设置 Http 请求类型
设置本次 Http 请求的方法类型,Http 有以下几种类型:

  • GET
  • POST
  • HEAD
  • CONNECT
  • OPTIONS
  • TRACE
  • PATCH
  • PUT
  • **DELETE
    这里就不做详细的解释了,可自行百度。最常用的就是前两种:GETPOST
conn.setRequestMethod("GET");
  1. 设置 Http 相关参数
    这一步主要是设置请求头的参数,我们前面那张大表就可以派上用场了。此时可以设置 Cookie、Content-Type、超时时间等等参数。比如设置超时时间为 3 秒:
conn.setConnectTimeout(3*1000); 
conn.setWirteTimeout(3 * 1000);
  1. 获取输入流
    通过getInputStream()方法获取网络输入流,此后可以通过此对象获取网络数据,如下:
InputStream in = conn.getInputStream();
  1. 关闭流
    网络流比较消耗资源,在使用完毕之后一定要将 Http 连接关掉:
conn.disconnect();

4. HttpURLConnection使用示例

还记得前面将现场的时候提到过,Android 系统规定只能在主线程操作 UI,这里再加上一条:

Android 系统不能在 UI 线程访问网络

所以我们需要开启一个子线程处理 Http 请求,这一节我们使用 40 节学习的 AsyncTask 来执行网络请求,拉取慕课网 Android 教程的首页信息。

4.1 后台网络任务

首先开启一个 AsyncTask,在后台打开一个 HttpURLConnection,地址是https://www.imooc.com/wiki/androidlesson,接着设置相应参数,然后获取网络数据输入流,即可读到页面信息了。

package com.emercy.myapplication;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        HttpURLConnection urlConnection = null;

        try {
            URL url = new URL("https://www.imooc.com/wiki/androidlesson");
            urlConnection = (HttpURLConnection) url.openConnection();

            int code = urlConnection.getResponseCode();
            if (code != 200) {
                throw new IOException("Invalid response from server: " + code);
            }

            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                Log.d("HttpTask", line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

        return null;
    }
}

4.2 首页布局

HTTPURLConnection 需要一个触发时机,所以在首页布局上我们放置一个 Button 用于触发 http 请求:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/start_http"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="100dp"
        android:text="发起 Http 请求" />
</LinearLayout>

4.3 MainActivity编写

核心逻辑是在 HttpTask 里面,MainActivity 里面主要是设置触发按钮监听器,然后在点击事件中启动 HttpTask 即可:


package com.emercy.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.start_http).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new HttpTask().execute();
            }
        });
    }
}

这里要记得,虽然在 HttpTask 中我们的代码是运行在doInBackground()方法中,但是启动 AsyncTask 的方法是调用eexecute()

编译运行界面如下:

http

点击“发起 HTTP 请求”启动 AsyncTask 启动 http 连接,然后输入接收到的数据到 Logcat,过滤“HttpTask”字段,观察日志:

http_result

以上是日志的片段,可以看到 Logcat 中的内容就是https://www.imooc.com/wiki/androidlesson页面的源代码,到此就获取成功了。

5. 小结

本节讲述了如何在 Android 中发起 http 请求,HttpURLConnection 的使用方式非常简单,但是需要你对 http 协议本身有一定的了解,作为开发者这个是必备的知识点。当然对于大型项目而言,需要涉及到 DNS、缓存、安全校验等等高级操作,这时候 HttpURLConnection 会显得有点输出乏力,这就需要第三方的框架出场了,万变不离其宗,所有的框架到了底层其实都是一样的基本原理,所以还是希望大家能够熟悉 http 协议,并掌握 HttpURLConnection 的用法。