蓝色天空.知识 · 实践 · 创造
我的收藏
Android 教程目录 156章
课程介绍
Android / LEARN BY DOING

7.1.3 Android HTTP请求方式:HttpURLConnection

核对 HttpURLConnection 标准六步调用流程、StreamTool 分块流读取、GET/POST/PUT 请求实现、Set-Cookie/Cookie 会话保持与 URL 重写方案,以及 Android 主线程禁网与现代 OkHttp/Retrofit 演进。

学完这一章,你能够

  • 核对 HttpURLConnection 标准六步调用流程、StreamTool 分块流读取、GET/POST/PUT 请求实现、Set-Cookie/Cookie 会话保持与 URL 重写方案,以及 Android 主线程禁网与现代 OkHttp/Retrofit 演进。

HttpURLConnection 定位与标准六步流程

`HttpURLConnection` 继承自 `URLConnection`,是 Android 标准库提供的轻量级 HTTP 客户端抽象类(Android 4.4 起底层默认实现已切换为 OkHttp,并默认透明支持 GZIP 压缩)。标准调用分为六步:① 构造 `URL` 对象;② 调用 `url.openConnection()` 强转为 `HttpURLConnection`(注:来源正文误拼为 `openCollection()`,正确方法名为 `openConnection()`);③ 调用 `setRequestMethod("GET"/"POST"/"PUT")` 指定请求方法;④ 设置 `setConnectTimeout()`、`setReadTimeout()` 与请求头;⑤ 校验 `getResponseCode()`(如是否为 `200`)并调用 `getInputStream()` 读取响应流;⑥ 在 `finally` 中关闭流并调用 `disconnect()` 释放资源。对于无需定制请求头的极简 GET 读取,也可用 `url.openStream()` 快捷获取输入流。实际工程中为简化连接池、重试与异步回调,通常直接使用 OkHttp 或 Retrofit + Kotlin 协程。

GET 请求读取图片与网页、网络权限及线程规则

由于 `conn.getInputStream()` 返回原始字节流,通常编写 `StreamTool.java` 使用 `1024` 字节缓冲区循环读入 `ByteArrayOutputStream` 并转为 `byte[]`,供 `BitmapFactory.decodeByteArray()` 解码图片或 `new String(data, "UTF-8")` 还原 HTML 源码。在 Android 端发起任何网络请求都必须在 `AndroidManifest.xml` 中声明 `android.permission.INTERNET`(Android 9+ 若访问明文 `http://` 还需配置 `networkSecurityConfig`),且必须将网络 I/O 放入工作线程(主线程发起网络会直接触发 `NetworkOnMainThreadException`),再通过 `Handler` 或主线程调度回写 UI。展示本地获取的 HTML 字符串给 `WebView` 时,优先使用 `loadDataWithBaseURL("", html, "text/html", "UTF-8", "")` 以避免 `loadData()` 常见的中文编码乱码。

POST 表单提交与参数编码要点

`openConnection()` 默认采用 `GET` 方法;改用 `POST` 提交表单时,需显式配置 `setRequestMethod("POST")`、`setDoOutput(true)`、`setDoInput(true)` 与 `setUseCaches(false)`,使用 `URLEncoder.encode(value, "UTF-8")` 对参数值做 URL 编码(确保 `+`、`&`、中文等特殊字符不被破坏)并设置 `Content-Type: application/x-www-form-urlencoded` 后写出到 `conn.getOutputStream()`。来源页面的 `HttpURLConnection.zip` 示例包已按停采规则登记在附件清单中,未联网抓取。

Cookie/Session 会话维持与 PUT 请求实践

Session 是服务端维护的会话状态机制,而 Cookie 只是最常见的客户端会话标识载体(包含名称、值、Domain、Path 与过期时间)。标准登录会话流程为:登录响应通过 `Set-Cookie` 头下发凭证,客户端经 `conn.getHeaderField("Set-Cookie")` 提取保存,后续请求通过 `conn.setRequestProperty("Cookie", cookie)` 回传;若凭证缺失或过期,服务端将返回 `401` 或跳转登录页。除请求头携带 Cookie 外,部分系统也采用 URL 重写(追加 `sessionid` 查询参数)或在 POST JSON 体中传递会话令牌。发送 `PUT` 请求与 `POST` 高度一致,只需将 `setRequestMethod("PUT")` 并写出请求体,同样可从响应头捕获 `Set-Cookie` 持久化。本站通过本地回环 HTTP 服务端实测了 GET 图片/HTML、POST 表单编码与 `Set-Cookie`、Cookie 鉴权与 URL 重写回退以及 PUT 请求全链路。

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

含完整源码 · 224 行
展开查看收起
python
"""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())
验证分块流读取二进制 PNG 与 UTF-8 HTML、POST 表单 URL 编码与 Set-Cookie 捕获、Cookie 鉴权/401/URL 重写及 PUT 会话返回。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a1829.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

若参数值中包含 '&'、'='、'+'、空格或中文字符,未经 URL 编码会破坏 application/x-www-form-urlencoded 的键值边界或引发解码乱码,编码后服务端才能无损还原原始字符串。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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