全国协议5人面授小班,企业级独立开发考核,转业者的IT软件工程师基地 登录/注册 | 如何报名
当前位置: Java   >  HTTP 使用详解
admin · 更新于 2021-08-06

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

1.2 Http 响应

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

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
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" />
代码块
  • 1

就可以访问 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();
代码块
  • 1
  • 2

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

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

4. HttpURLConnection使用示例

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

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

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

4.1 后台网络任务

首先开启一个 AsyncTask,在后台打开一个 HttpURLConnection,接着设置相应参数,然后获取网络数据输入流,即可读到页面信息了。

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("");
            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;
    }}
代码块
  • 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

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>
代码块
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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();
            }
        });
    }}
代码块
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

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

编译运行界面如下:

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

以上是日志的片段,可以看到 Logcat 中的内容就是页面的源代码,到此就获取成功了。

5. 小结

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


为什么选择汉码未来