蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本地回环 HttpURLConnection GET/POST/Cookie/URL重写/PUT 全链路实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-httpurlconnection.py
explore-tutorial-httpurlconnection.py224 行
"""Offline Android HttpURLConnection GET/POST/Cookie/PUT loopback verifier (Ch 87: tutorial-httpurlconnection)."""
from __future__ import annotations

import json
import sys
import threading
import urllib.error
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"

MOCK_PNG = b"\x89PNG\r\n\x1a\nMOCK_IMAGE_PAYLOAD"
MOCK_HTML = "<html><head><meta charset='utf-8'></head><body><h1>欢迎学习网络编程</h1></body></html>"
VALID_SID = "SESSIONID=abc123xyz"


def stream_tool_read(resp, chunk_size: int = 16) -> bytes:
    """Equivalent to StreamTool.read(InputStream) using chunked buffer reads."""
    buf = bytearray()
    while True:
        chunk = resp.read(chunk_size)
        if not chunk:
            break
        buf.extend(chunk)
    return bytes(buf)


class HttpUrlConnHandler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, format: str, *args) -> None:
        return

    def _send(self, code: int, body: bytes, content_type: str = "text/plain; charset=utf-8", extra: dict | None = None):
        self.send_response(code)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(body)))
        if extra:
            for k, v in extra.items():
                self.send_header(k, v)
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self) -> None:
        parsed = urllib.parse.urlparse(self.path)
        if parsed.path == "/image.png":
            self._send(200, MOCK_PNG, "image/png")
        elif parsed.path == "/page.html":
            self._send(200, MOCK_HTML.encode("utf-8"), "text/html; charset=utf-8")
        elif parsed.path == "/profile":
            cookie = self.headers.get("Cookie", "")
            qs = urllib.parse.parse_qs(parsed.query)
            if VALID_SID in cookie:
                self._send(200, json.dumps({"auth": "cookie", "user": "alice"}).encode("utf-8"), "application/json")
            elif qs.get("sessionid") == ["abc123xyz"]:
                self._send(200, json.dumps({"auth": "url_rewrite", "user": "alice"}).encode("utf-8"), "application/json")
            else:
                self._send(401, json.dumps({"auth": "missing"}).encode("utf-8"), "application/json")
        else:
            self._send(404, b"not found")

    def do_POST(self) -> None:
        length = int(self.headers.get("Content-Length", "0"))
        raw = self.rfile.read(length).decode("utf-8")
        form = urllib.parse.parse_qs(raw)
        if self.path == "/login":
            number = form.get("number", [""])[0]
            passwd = form.get("passwd", [""])[0]
            if number == "13800138000" and passwd == "p@ss+123":
                self._send(
                    200,
                    json.dumps({"login": "ok", "number": number}).encode("utf-8"),
                    "application/json",
                    extra={"Set-Cookie": f"{VALID_SID}; Path=/; HttpOnly"},
                )
            else:
                self._send(403, json.dumps({"login": "denied"}).encode("utf-8"), "application/json")
        else:
            self._send(404, b"not found")

    def do_PUT(self) -> None:
        length = int(self.headers.get("Content-Length", "0"))
        raw = self.rfile.read(length).decode("utf-8")
        form = urllib.parse.parse_qs(raw)
        body = json.dumps({
            "method": "PUT",
            "mobile": form.get("mobile", [""])[0],
            "remember_me": form.get("remember_me", [""])[0],
        }).encode("utf-8")
        self._send(200, body, "application/json", extra={"Set-Cookie": f"{VALID_SID}; Path=/"})


def main() -> None:
    cases = []
    server = ThreadingHTTPServer(("127.0.0.1", 0), HttpUrlConnHandler)
    port = server.server_address[1]
    base = f"http://127.0.0.1:{port}"
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    try:
        # Case 1: GET binary image & UTF-8 HTML using StreamTool chunked reader
        with urllib.request.urlopen(f"{base}/image.png", timeout=5) as r_img:
            img_status = r_img.status
            img_data = stream_tool_read(r_img)
        with urllib.request.urlopen(f"{base}/page.html", timeout=5) as r_html:
            html_status = r_html.status
            html_text = stream_tool_read(r_html).decode("utf-8")
        actual1 = {
            "img_status": img_status,
            "img_matches": img_data == MOCK_PNG,
            "html_status": html_status,
            "html_contains_cn": "欢迎学习网络编程" in html_text,
        }
        expected1 = {
            "img_status": 200,
            "img_matches": True,
            "html_status": 200,
            "html_contains_cn": True,
        }
        cases.append({
            "name": "httpurlconnection_get_binary_and_html",
            "summary": "Verify GET request with chunked stream reading for PNG bytes and UTF-8 HTML content.",
            "expected": expected1,
            "actual": actual1,
            "passed": actual1 == expected1,
        })

        # Case 2: POST URL-encoded form parameters (URLEncoder.encode equivalent) + Set-Cookie capture
        encoded = urllib.parse.urlencode({"number": "13800138000", "passwd": "p@ss+123"}).encode("utf-8")
        req_post = urllib.request.Request(
            f"{base}/login",
            data=encoded,
            method="POST",
            headers={"Content-Type": "application/x-www-form-urlencoded", "Cache-Control": "no-cache"},
        )
        with urllib.request.urlopen(req_post, timeout=5) as r_post:
            post_status = r_post.status
            set_cookie = r_post.headers.get("Set-Cookie", "")
            post_json = json.loads(stream_tool_read(r_post).decode("utf-8"))
        cookie_pair = set_cookie.split(";", 1)[0]
        actual2 = {
            "status": post_status,
            "login": post_json["login"],
            "captured_cookie": cookie_pair,
            "plus_encoded_safely": "%2B" in encoded.decode("ascii"),
        }
        expected2 = {
            "status": 200,
            "login": "ok",
            "captured_cookie": VALID_SID,
            "plus_encoded_safely": True,
        }
        cases.append({
            "name": "httpurlconnection_post_form_and_set_cookie",
            "summary": "Verify POST form URL encoding (preserving special chars like '+') and Set-Cookie response capture.",
            "expected": expected2,
            "actual": actual2,
            "passed": actual2 == expected2,
        })

        # Case 3: Cookie header replay vs missing Cookie 401 vs URL rewriting fallback
        unauth_code = 0
        try:
            urllib.request.urlopen(f"{base}/profile", timeout=5)
        except urllib.error.HTTPError as exc:
            unauth_code = exc.code
        req_cookie = urllib.request.Request(f"{base}/profile", headers={"Cookie": cookie_pair})
        with urllib.request.urlopen(req_cookie, timeout=5) as r_auth:
            auth_cookie_json = json.loads(stream_tool_read(r_auth).decode("utf-8"))
        with urllib.request.urlopen(f"{base}/profile?sessionid=abc123xyz", timeout=5) as r_rewrite:
            auth_rewrite_json = json.loads(stream_tool_read(r_rewrite).decode("utf-8"))
        actual3 = {
            "unauth_code": unauth_code,
            "cookie_auth": auth_cookie_json["auth"],
            "url_rewrite_auth": auth_rewrite_json["auth"],
        }
        expected3 = {
            "unauth_code": 401,
            "cookie_auth": "cookie",
            "url_rewrite_auth": "url_rewrite",
        }
        cases.append({
            "name": "cookie_session_and_url_rewriting",
            "summary": "Verify Cookie header authentication, 401 rejection without session, and URL-rewriting fallback.",
            "expected": expected3,
            "actual": actual3,
            "passed": actual3 == expected3,
        })

        # Case 4: PUT request with body payload and Set-Cookie persistence
        put_data = urllib.parse.urlencode({"mobile": "13900001111", "remember_me": "1"}).encode("utf-8")
        req_put = urllib.request.Request(
            f"{base}/session",
            data=put_data,
            method="PUT",
            headers={"Content-Type": "application/x-www-form-urlencoded"},
        )
        with urllib.request.urlopen(req_put, timeout=5) as r_put:
            put_json = json.loads(stream_tool_read(r_put).decode("utf-8"))
            put_cookie = r_put.headers.get("Set-Cookie", "").split(";", 1)[0]
        actual4 = {"put_json": put_json, "put_cookie": put_cookie}
        expected4 = {
            "put_json": {"method": "PUT", "mobile": "13900001111", "remember_me": "1"},
            "put_cookie": VALID_SID,
        }
        cases.append({
            "name": "httpurlconnection_put_request",
            "summary": "Verify HTTP PUT method submission with form body and Set-Cookie extraction.",
            "expected": expected4,
            "actual": actual4,
            "passed": actual4 == expected4,
        })
    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-httpurlconnection-lab/explore-tutorial-httpurlconnection.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-httpurlconnection.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1905.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习