"""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())
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/android-tutorial-http-response-header-lab/explore-tutorial-http-response-header.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-http-response-header.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1903.zip