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

运行本地回环 WebView DownloadListener 外部拉起、后台 GET 下载与 setDoOutput 405 陷阱实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-webview-download-file.py
explore-tutorial-webview-download-file.py181 行
"""Offline Android WebView DownloadListener & custom download thread loopback verifier (Ch 98: tutorial-webview-download-file)."""
from __future__ import annotations

import hashlib
import http.client
import json
import re
import sys
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

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

APK_BYTES = b"PK\x03\x04MOCK_ANDROID_APK_ARCHIVE_CONTENT_2026"
APK_SHA = hashlib.sha256(APK_BYTES).hexdigest()


class WebViewDownloadHandler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"
    last_method = ""

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

    def do_GET(self) -> None:
        WebViewDownloadHandler.last_method = "GET"
        if self.path == "/files/client_app.apk":
            self.send_response(200)
            self.send_header("Content-Type", "application/vnd.android.package-archive")
            self.send_header("Content-Disposition", 'attachment; filename="client_app.apk"')
            self.send_header("Content-Length", str(len(APK_BYTES)))
            self.end_headers()
            self.wfile.write(APK_BYTES)
        else:
            self.send_response(404)
            self.send_header("Content-Length", "0")
            self.end_headers()

    def do_POST(self) -> None:
        WebViewDownloadHandler.last_method = "POST"
        self.send_response(405)
        self.send_header("Allow", "GET")
        self.send_header("Content-Length", "0")
        self.end_headers()


def main() -> None:
    cases = []
    server = ThreadingHTTPServer(("127.0.0.1", 0), WebViewDownloadHandler)
    port = server.server_address[1]
    dl_url = f"http://127.0.0.1:{port}/files/client_app.apk"
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    try:
        # Case 1: DownloadListener callback parameters & external browser Intent.ACTION_VIEW dispatch
        event = {
            "url": dl_url,
            "userAgent": "Mozilla/5.0 (Linux; Android 14)",
            "contentDisposition": 'attachment; filename="client_app.apk"',
            "mimetype": "application/vnd.android.package-archive",
            "contentLength": len(APK_BYTES),
        }
        m = re.search(r'filename="?([^";]+)"?', event["contentDisposition"])
        intent = {
            "action": "android.intent.action.VIEW",
            "data_uri": event["url"],
            "parsed_filename": m.group(1) if m else "unknown",
        }
        actual1 = {
            "action": intent["action"],
            "filename": intent["parsed_filename"],
            "content_length": event["contentLength"],
        }
        expected1 = {
            "action": "android.intent.action.VIEW",
            "filename": "client_app.apk",
            "content_length": len(APK_BYTES),
        }
        cases.append({
            "name": "download_listener_external_intent",
            "summary": "Verify DownloadListener.onDownloadStart metadata extraction and external Intent.ACTION_VIEW dispatch.",
            "expected": expected1,
            "actual": actual1,
            "passed": actual1 == expected1,
        })

        # Case 2: Custom background thread GET download to temporary storage with SHA-256 verification
        with tempfile.TemporaryDirectory() as tmp:
            out_path = Path(tmp) / "client_app.apk"
            result_box: dict = {}

            def bg_download() -> None:
                c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
                c.request("GET", "/files/client_app.apk")
                r = c.getresponse()
                result_box["status"] = r.status
                with out_path.open("wb") as fh:
                    while True:
                        chunk = r.read(16)
                        if not chunk:
                            break
                        fh.write(chunk)
                c.close()

            t = threading.Thread(target=bg_download)
            t.start()
            t.join()
            actual2 = {
                "http_status": result_box["status"],
                "server_saw_method": WebViewDownloadHandler.last_method,
                "saved_size": out_path.stat().st_size,
                "sha_matches": hashlib.sha256(out_path.read_bytes()).hexdigest() == APK_SHA,
            }
            expected2 = {
                "http_status": 200,
                "server_saw_method": "GET",
                "saved_size": len(APK_BYTES),
                "sha_matches": True,
            }
            cases.append({
                "name": "custom_background_thread_download",
                "summary": "Verify custom background download thread streams bytes cleanly over GET and verifies SHA-256.",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

        # Case 3: Verify why setting setDoOutput(true) on a GET download breaks static file endpoints (405 POST)
        c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
        c.request("POST", "/files/client_app.apk", body=b"")
        r_post = c.getresponse()
        r_post.read()
        c.close()
        actual3 = {
            "setDoOutput_true_forces_post_status": r_post.status,
            "allow_header": r_post.getheader("Allow"),
            "fix_keep_do_output_false_for_get": True,
        }
        expected3 = {
            "setDoOutput_true_forces_post_status": 405,
            "allow_header": "GET",
            "fix_keep_do_output_false_for_get": True,
        }
        cases.append({
            "name": "set_do_output_get_to_post_pitfall",
            "summary": "Verify legacy HttpURLConnection setDoOutput(true) converts GET into POST (causing 405) and must be omitted for GET.",
            "expected": expected3,
            "actual": actual3,
            "passed": actual3 == expected3,
        })

        # Case 4: Storage permission transition (Android <= 9 WRITE_EXTERNAL_STORAGE vs Android 10+ MediaStore.Downloads / DownloadManager)
        def storage_strategy(api_level: int) -> dict:
            if api_level >= 29:
                return {"api": "MediaStore.Downloads_or_DownloadManager", "needs_write_external_perm": False}
            return {"api": "Environment.getExternalStorageDirectory", "needs_write_external_perm": True}

        actual4 = {"api23": storage_strategy(23), "api29_plus": storage_strategy(29)}
        expected4 = {
            "api23": {"api": "Environment.getExternalStorageDirectory", "needs_write_external_perm": True},
            "api29_plus": {"api": "MediaStore.Downloads_or_DownloadManager", "needs_write_external_perm": False},
        }
        cases.append({
            "name": "modern_scoped_storage_download_policy",
            "summary": "Verify Android 10 (API 29+) MediaStore.Downloads / DownloadManager requires no WRITE_EXTERNAL_STORAGE permission.",
            "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-webview-download-file-lab/explore-tutorial-webview-download-file.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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