蓝色天空网mbsky.com · 知识 · 实践 · 创造Android · 本地阅读预览
教程 / 移动开发 / Android

7.5.4 WebView文件下载

核对 WebView.setDownloadListener 监听文件下载的两种实现路径(拉起系统浏览器 Intent.ACTION_VIEW 与自定义后台线程下载),勘正原下载线程 setDoOutput(true) 导致 GET 变 POST 的陷阱,并补充 Android 10+ MediaStore.Downloads / DownloadManager 现代落盘策略。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

方案 1:通过 DownloadListener 交由系统浏览器下载

`WebView` 默认不会自动将网页中的文件下载链接保存到本地磁盘,必须通过 `webView.setDownloadListener(...)` 注册 `DownloadListener` 并重写 `onDownloadStart(url, userAgent, contentDisposition, mimetype, contentLength)`。最省力的方案是在回调中将 `url` 封装为 `Intent(Intent.ACTION_VIEW, Uri.parse(url))` 并调用 `startActivity(intent)`,将下载任务移交给设备已安装的浏览器或系统下载组件处理(存在多个浏览器时会弹出选择器;需注意如果目标下载受登录 Cookie 保护,外部浏览器因不共享应用 WebView Cookie 可能会鉴权失败,此时需采用应用内下载或向 `DownloadManager.Request` 传递 Cookie 请求头)。

方案 2:自定义后台下载线程、常见陷阱勘误与分区存储演进

若需要自定义保存路径、文件名或应用内进度条,可在 `onDownloadStart()` 中启动后台工作线程(或交由系统 `DownloadManager` / OkHttp)读取网络流写入磁盘,并在 `finally` 中安全关闭输入/输出流。编写 `HttpURLConnection` 下载线程时须特别规避三处关键要点:① **调用顺序**:所有超时、请求方法与请求头(含 `Cookie`、`User-Agent`)都必须在 `conn.getInputStream()` 之前配置完毕;② **源码勘误(GET 误变 POST)**:来源 `DownLoadThread.java` 对下载链接调用了 `conn.setDoOutput(true)`,在 Java/Android `HttpURLConnection` 中这会把默认 `GET` 自动改为 `POST`,导致只允许 `GET` 的静态文件服务器返回 `405 Method Not Allowed`,下载文件应切勿调用 `setDoOutput(true)`;③ **现代存储权限**:旧版清单依赖 `WRITE_EXTERNAL_STORAGE` 写入外部根目录(`MOUNT_UNMOUNT_FILESYSTEMS` 为系统权限普通应用无效),在 Android 10(API 29)及以上分区存储环境下,推荐直接写入应用专属目录 `getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)` 或通过 `MediaStore.Downloads` / `DownloadManager` 写入公共下载目录,无需申请存储权限。本站本地回环 HTTP 服务端实测了外部 Intent 元数据提取、后台 GET 线程下载 SHA-256 校验以及 `POST` 触发 `405` 的对照实验。

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

python · 阅读源码
"""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())
预期结果 · 待实际运行核验
  • 验证 onDownloadStart 文件名解析与 ACTION_VIEW Intent、后台线程 GET 下载 SHA-256 一致、POST 触发 405 勘误及 API 29+ 免权限策略。
运行本地回环 WebView DownloadListener 外部拉起、后台 GET 下载与 setDoOutput 405 陷阱实测

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:3e361384631c5182d2860b0785d261230a8156fb43221ae4e6221147942af43e

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载7.5.4 WebView文件下载实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:e1c36a2c5f9b55ae857863ec386337bef130d563b0553a96b7e33e38b029b13f

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么在基于 HttpURLConnection 编写 WebView 文件下载线程时,不应调用 conn.setDoOutput(true)?

展开参考解答

在 HttpURLConnection 的实现中,一旦设置 setDoOutput(true) 会将未显式指定的 GET 请求隐式切换为 POST 请求;许多静态文件或 CDN 下载节点仅允许 GET/HEAD,从而返回 405 Method Not Allowed 导致下载失败。

规范与官方依据