7.1.2 Android Http请求头与响应头的学习
系统核对 30 项 HTTP 请求头与 18 项 HTTP 响应头对照表,并通过本地回环 HTTP 服务端实测 Location 302 重定向、gzip Content-Encoding 压缩、application/pdf Content-Type、Refresh 定时跳转、Content-Disposition 附件下载及 ETag/304 协商缓存。
学完这一章,你能够
- 系统核对 30 项 HTTP 请求头与 18 项 HTTP 响应头对照表,并通过本地回环 HTTP 服务端实测 Location 302 重定向、gzip Content-Encoding 压缩、application/pdf Content-Type、Refresh 定时跳转、Content-Disposition 附件下载及 ETag/304 协商缓存。
HTTP 请求消息头结构与完整对照
HTTP 请求报文首行为请求行(请求方法 + 资源路径 + 协议版本),紧随其后的一系列 `Key: Value` 请求头用于向服务端声明客户端能力、缓存条件、身份凭证与来源信息;服务端可按业务策略决定是否响应这些提示。下方请求头对照表系统整理了内容协商(`Accept`、`Accept-Encoding`、`Accept-Language`)、条件请求与缓存(`Cache-Control`、`If-Modified-Since`、`If-None-Match`、`If-Range`)、分块续传(`Range`)以及会话认证(`Authorization`、`Cookie`)等 30 项核心字段。
HTTP 响应消息头结构与完整对照
HTTP 响应报文首行为状态行(协议版本 + 状态码 + 原因短语),例如返回 `302` 时通常会配合 `Location` 响应头指示客户端跳转至新的目标地址。下方响应头对照表涵盖范围传输声明(`Accept-Ranges`、`Content-Range`)、实体元信息(`Content-Type`、`Content-Encoding`、`Content-Length`)、缓存验证(`Cache-Control`、`ETag`、`Expires`、`Last-Modified`、`Age`)与重定向/认证控制等 18 项常用响应头。
响应头实战验证:重定向、GZIP 压缩与 MIME 类型
原教程使用 Java Servlet(在 `web.xml` 注册 `<servlet>` 与 `<servlet-mapping>`)逐一验证常用响应头,本站在本地 `127.0.0.1` 回环 HTTP 服务中复现了完全一致的协议交互:第一,设置状态码 `302` 与 `Location` 头可引导客户端跳转至目标路径;第二,使用 GZIP 压缩文本并声明 `Content-Encoding: gzip` 与压缩后 `Content-Length` 能显著减小长文本流量(本站实测 497 字节英文段落压缩后明显变小,而极短古诗文本因 GZIP 头部开销反而比原文更大,与教程观察一致);第三,设置 `Content-Type: application/pdf`(或 `image/jpeg`、`text/html` 等 MIME 类型)可告知客户端按对应文档或媒体类型解析渲染输出流。
响应头实战验证:Refresh 跳转与 Content-Disposition 下载
第四,通过 `Refresh: 2` 可令浏览器每隔 2 秒重新请求当前地址刷新内容,通过 `Refresh: 5;url='...'` 则在停留 5 秒后自动跳转到指定页面(注意 `Refresh` 虽被主流浏览器广泛兼容,但属于非标准扩展头);第五,设置 `Content-Disposition: attachment;filename=Android.pdf` 会指示客户端将响应体作为附件保存下载而非直接内嵌预览。此外,本站回环实验还实测了 `ETag` 与 `If-None-Match` 协作返回 `304 Not Modified` 空体的协商缓存机制。来源页面的 `HttpTest.zip` 示例包因停采约束未联网下载,已登记至附件清单。
HTTP Request Header 请求头对照表
| 请求头 | 作用说明 | 典型示例 |
|---|---|---|
| Accept | 声明客户端可接收的 MIME 媒体类型 | Accept: text/plain, text/html |
| Accept-Charset | 声明客户端偏好的字符编码集(现代客户端通常默认 UTF-8) | Accept-Charset: utf-8 |
| Accept-Encoding | 声明客户端支持的内容压缩编码算法 | Accept-Encoding: gzip, deflate |
| Accept-Language | 声明客户端偏好的自然语言及地区 | Accept-Language: zh-CN, en |
| Accept-Ranges | 标识范围请求单位(注:RFC 9110 中 Accept-Ranges 属于响应头,客户端分段请求应使用 Range) | Accept-Ranges: bytes |
| Authorization | 携带客户端向服务端提交的认证凭据(如 Basic 或 Bearer 令牌) | Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== |
| Cache-Control | 指示请求链与缓存代理应遵循的缓存指令 | Cache-Control: no-cache |
| Connection | 控制当前 TCP 连接在请求结束后是否保持复用(HTTP/1.1 默认 keep-alive) | Connection: close |
| Cookie | 将目标域名与路径下匹配的本地 Cookie 键值对随请求回传服务端 | Cookie: SID=abc123; theme=dark |
| Content-Length | 以十进制字节数指明请求实体主体的精确长度 | Content-Length: 348 |
| Content-Type | 指明请求实体主体的 MIME 类型及字符集参数 | Content-Type: application/x-www-form-urlencoded |
| Date | 记录报文构造发送的 GMT 日期时间 | Date: Tue, 15 Nov 2010 08:12:31 GMT |
| Expect | 声明客户端期望服务端满足的特定行为(常用于大请求体的 100-continue 预检) | Expect: 100-continue |
| From | 标明发起请求的客户端控制者邮箱地址(常见于合规爬虫) | From: user@example.com |
| Host | 指定目标服务器的主机名及可选端口号(HTTP/1.1 必填请求头) | Host: api.example.com |
| If-Match | 仅当服务端资源当前 ETag 与指定值匹配时才执行请求(常用于防并发覆盖) | If-Match: "etag-android-v1" |
| If-Modified-Since | 若资源在指定时间后发生修改则返回新内容,否则返回 304 | If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT |
| If-None-Match | 携带本地缓存的 ETag 与服务端比对,一致则返回 304 Not Modified | If-None-Match: "etag-android-v1" |
| If-Range | 配合 Range 续传:若实体未变则返回 206 分段,已变则返回 200 完整实体 | If-Range: "etag-android-v1" |
| If-Unmodified-Since | 仅当资源在指定时间之后未被修改时才执行操作,否则返回 412 | If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT |
| Max-Forwards | 限制 TRACE/OPTIONS 请求经由代理或网关转发的最大跳数 | Max-Forwards: 10 |
| Pragma | HTTP/1.0 遗留缓存控制指令,现代场景优先使用 Cache-Control | Pragma: no-cache |
| Proxy-Authorization | 向中间代理服务器提交的身份验证凭据 | Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== |
| Range | 请求资源的指定字节区间以实现多线程分段下载或断点续传 | Range: bytes=500-999 |
| Referer | 标明触发本次请求的前序来源页面地址(常用于防盗链或统计) | Referer: https://example.org/index |
| TE | 声明客户端愿意接受的传输编码及是否支持尾部头字段(trailers) | TE: trailers, deflate;q=0.5 |
| Upgrade | 提议将当前连接协议升级为目标协议(如 WebSocket) | Upgrade: websocket |
| User-Agent | 标识发起请求的客户端应用、内核与操作系统信息 | User-Agent: AndroidLab/1.0 |
| Via | 记录报文途径的中间代理或网关协议版本与标识 | Via: 1.1 proxy.example.org |
| Warning | 携带关于消息实体转换或缓存状态的附加告警信息(RFC 9111 已废弃) | Warning: 199 - Miscellaneous warning |
HTTP Response Header 响应头对照表
| 响应头 | 作用说明 | 典型示例 |
|---|---|---|
| Accept-Ranges | 告知客户端服务端是否支持按字节范围分段请求 | Accept-Ranges: bytes |
| Age | 对象在代理缓存中已停留的估算秒数(非负整数) | Age: 12 |
| Allow | 列举目标资源允许的 HTTP 方法(配合 405 Method Not Allowed 使用) | Allow: GET, HEAD |
| Cache-Control | 控制客户端及共享代理对当前响应的缓存策略与有效期 | Cache-Control: no-cache |
| Content-Encoding | 指明响应体采用的压缩编码方式(客户端需据此解压) | Content-Encoding: gzip |
| Content-Language | 说明响应内容面向的自然语言 | Content-Language: zh-CN, en |
| Content-Length | 响应主体的精确字节长度(经压缩时为压缩后字节数) | Content-Length: 348 |
| Content-Location | 指明当前返回数据所对应的具体替代资源路径 | Content-Location: /index.htm |
| Content-MD5 | 响应体内容的 Base64 编码 MD5 摘要(RFC 7231 已移除) | Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ== |
| Content-Range | 在 206 分段响应中标明当前字节区间与完整文件总大小 | Content-Range: bytes 21010-47021/47022 |
| Content-Type | 指明响应实体的 MIME 类型与字符编码 | Content-Type: application/pdf |
| Date | 源服务器生成并发送该响应的 GMT 时间戳 | Date: Tue, 15 Nov 2010 08:12:31 GMT |
| ETag | 资源特定版本的实体校验标签,供后续条件请求比对 | ETag: "etag-android-v1" |
| Expires | 指定响应缓存失效的绝对日期时间(优先级低于 Cache-Control max-age) | Expires: Thu, 01 Dec 2010 16:00:00 GMT |
| Last-Modified | 源服务器记录的该资源最近一次修改时间 | Last-Modified: Tue, 15 Nov 2010 12:45:26 GMT |
| Location | 配合 3xx 状态码指示重定向目标地址,或配合 201 指示新创建资源地址 | Location: /redirected-target |
| Pragma | 兼容 HTTP/1.0 代理的缓存控制字段 | Pragma: no-cache |
| Proxy-Authenticate | 配合 407 响应说明代理服务器要求的认证方案及参数 | Proxy-Authenticate: Basic |
运行本地回环 HTTP 重定向、GZIP 压缩、PDF MIME、Refresh、附件下载与 ETag/304 实测
"""Offline Android HTTP Request/Response Headers loopback verifier (Ch 86: tutorial-http-response-header)."""
from __future__ import annotations
import gzip
import http.client
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"
LONG_TEXT = (
"Fresh air and sunshine can have an amazing effect on our feelings. "
"Sometimes when we are feeling down, all that we need to do is simply to go "
"outside and breathe. Movement and exercise is also a fantastic way to feel better. "
"Positive emotions can be generated by motion. So if we start to feel down, "
"take some deep breathes, go outside, feel the fresh air, "
"let the sun hit our face, go for a hike, a walk, a bike ride, "
"a swim, a run, whatever. We will feel better if we do this."
).encode("utf-8")
SHORT_TEXT = "床前明月光,疑是地上霜。".encode("utf-8")
MOCK_PDF = b"%PDF-1.4\n%Android coding spec mock\n%%EOF\n"
RESOURCE_ETAG = '"etag-android-v1"'
class HeaderDemoHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, format: str, *args) -> None:
return
def do_GET(self) -> None:
if self.path == "/ServletOne":
self.send_response(302)
self.send_header("Location", "/redirected-target")
self.send_header("Content-Length", "0")
self.end_headers()
elif self.path == "/redirected-target":
body = b"redirected-ok"
self.send_response(200)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif self.path == "/ServletTwo":
gz = gzip.compress(LONG_TEXT, mtime=0)
self.send_response(200)
self.send_header("Content-Encoding", "gzip")
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(gz)))
self.end_headers()
self.wfile.write(gz)
elif self.path == "/ServletThree":
self.send_response(200)
self.send_header("Content-Type", "application/pdf")
self.send_header("Content-Length", str(len(MOCK_PDF)))
self.end_headers()
self.wfile.write(MOCK_PDF)
elif self.path == "/ServletFour":
body = b"refresh-countdown"
self.send_response(200)
self.send_header("Refresh", "5;url='/redirected-target'")
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif self.path == "/ServletFive":
self.send_response(200)
self.send_header("Content-Disposition", "attachment;filename=Android.pdf")
self.send_header("Content-Length", str(len(MOCK_PDF)))
self.end_headers()
self.wfile.write(MOCK_PDF)
elif self.path == "/cacheable":
inm = self.headers.get("If-None-Match")
if inm == RESOURCE_ETAG:
self.send_response(304)
self.send_header("ETag", RESOURCE_ETAG)
self.send_header("Cache-Control", "no-cache")
self.send_header("Content-Length", "0")
self.end_headers()
else:
body = json.dumps({
"accept": self.headers.get("Accept"),
"lang": self.headers.get("Accept-Language"),
"ua": self.headers.get("User-Agent"),
"referer": self.headers.get("Referer"),
}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("ETag", RESOURCE_ETAG)
self.send_header("Accept-Ranges", "bytes")
self.send_header("Cache-Control", "no-cache")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
def main() -> None:
cases = []
server = ThreadingHTTPServer(("127.0.0.1", 0), HeaderDemoHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
# Case 1: 302 Location redirect
conn.request("GET", "/ServletOne")
r1 = conn.getresponse()
r1.read()
loc = r1.getheader("Location")
conn.request("GET", loc)
r1b = conn.getresponse()
body1 = r1b.read().decode("utf-8")
actual1 = {"status": r1.status, "location": loc, "followed_status": r1b.status, "body": body1}
expected1 = {"status": 302, "location": "/redirected-target", "followed_status": 200, "body": "redirected-ok"}
cases.append({
"name": "location_302_redirect",
"summary": "Verify HTTP 302 status with Location header redirect and target retrieval.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Content-Encoding: gzip compression & short-string overhead observation
conn.request("GET", "/ServletTwo", headers={"Accept-Encoding": "gzip"})
r2 = conn.getresponse()
raw_gz = r2.read()
decompressed = gzip.decompress(raw_gz)
short_gz = gzip.compress(SHORT_TEXT, mtime=0)
actual2 = {
"encoding": r2.getheader("Content-Encoding"),
"long_compressed_smaller": len(raw_gz) < len(LONG_TEXT),
"roundtrip_exact": decompressed == LONG_TEXT,
"short_gzip_larger_than_raw": len(short_gz) > len(SHORT_TEXT),
}
expected2 = {
"encoding": "gzip",
"long_compressed_smaller": True,
"roundtrip_exact": True,
"short_gzip_larger_than_raw": True,
}
cases.append({
"name": "content_encoding_gzip_compression",
"summary": "Verify gzip Content-Encoding reduces long text size while adding header overhead on very short strings.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Content-Type: application/pdf streaming
conn.request("GET", "/ServletThree")
r3 = conn.getresponse()
pdf_bytes = r3.read()
actual3 = {
"content_type": r3.getheader("Content-Type"),
"starts_with_pdf_magic": pdf_bytes.startswith(b"%PDF-1.4"),
"byte_len": len(pdf_bytes),
}
expected3 = {
"content_type": "application/pdf",
"starts_with_pdf_magic": True,
"byte_len": len(MOCK_PDF),
}
cases.append({
"name": "content_type_pdf_mime",
"summary": "Verify Content-Type: application/pdf MIME header and binary PDF byte stream.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Refresh header timed navigation
conn.request("GET", "/ServletFour")
r4 = conn.getresponse()
body4 = r4.read().decode("utf-8")
actual4 = {"refresh": r4.getheader("Refresh"), "body": body4}
expected4 = {"refresh": "5;url='/redirected-target'", "body": "refresh-countdown"}
cases.append({
"name": "refresh_header_redirect",
"summary": "Verify Refresh response header format for timed reload/redirection.",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
# Case 5: Content-Disposition attachment download
conn.request("GET", "/ServletFive")
r5 = conn.getresponse()
dl_bytes = r5.read()
actual5 = {
"content_disposition": r5.getheader("Content-Disposition"),
"bytes_match": dl_bytes == MOCK_PDF,
}
expected5 = {
"content_disposition": "attachment;filename=Android.pdf",
"bytes_match": True,
}
cases.append({
"name": "content_disposition_attachment",
"summary": "Verify Content-Disposition: attachment;filename=Android.pdf forces download semantics.",
"expected": expected5,
"actual": actual5,
"passed": actual5 == expected5,
})
# Case 6: Request headers negotiation + ETag / If-None-Match -> 304 Not Modified
req_hdrs = {
"Accept": "application/json",
"Accept-Language": "zh-CN,en",
"User-Agent": "AndroidLab/1.0",
"Referer": "http://127.0.0.1/index",
}
conn.request("GET", "/cacheable", headers=req_hdrs)
r6a = conn.getresponse()
echo = json.loads(r6a.read().decode("utf-8"))
etag = r6a.getheader("ETag")
accept_ranges = r6a.getheader("Accept-Ranges")
conn.request("GET", "/cacheable", headers={"If-None-Match": etag})
r6b = conn.getresponse()
body6b = r6b.read()
conn.close()
actual6 = {
"first_status": r6a.status,
"echo_lang": echo["lang"],
"echo_ua": echo["ua"],
"accept_ranges": accept_ranges,
"etag": etag,
"conditional_status": r6b.status,
"conditional_body_len": len(body6b),
}
expected6 = {
"first_status": 200,
"echo_lang": "zh-CN,en",
"echo_ua": "AndroidLab/1.0",
"accept_ranges": "bytes",
"etag": RESOURCE_ETAG,
"conditional_status": 304,
"conditional_body_len": 0,
}
cases.append({
"name": "request_headers_and_etag_304",
"summary": "Verify request headers (Accept/Accept-Language/User-Agent/Referer) and ETag/If-None-Match 304 validation.",
"expected": expected6,
"actual": actual6,
"passed": actual6 == expected6,
})
finally:
server.shutdown()
server.server_close()
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
sys.exit(main())
- 验证 302+Location 跳转、gzip 压缩长短文本体积差异、application/pdf 响应、Refresh 头部、Content-Disposition 附件与 If-None-Match 304。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:6aa7277d7a27d56963db396f16da27b82b672a87763b46efe8ae426715af00be
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:239557476f3b0e925f917c6541b9b49f5201c8858b2461b04e87d1e95e0daea8
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 HTTP 协商缓存中,ETag/If-None-Match 与 Last-Modified/If-Modified-Since 如何协同避免重复下载未变化的资源?
展开参考解答
首次响应由服务端返回 ETag 或 Last-Modified;客户端再次请求时通过 If-None-Match 或 If-Modified-Since 带回该标识,若服务端资源未改动则直接返回 304 Not Modified 且无响应体,客户端即可复用本地缓存。