7.1.4 Android HTTP请求方式:HttpClient
核对 Apache HttpClient 历史用法(HttpGet、HttpPost、UrlEncodedFormEntity、Cookie/302 手动重定向模拟登录与 HttpPut),明确说明其在 Android 6.0(API 23)被移除的历史背景与 OkHttp/HttpURLConnection 迁移路径。
学完这一章,你能够
- 核对 Apache HttpClient 历史用法(HttpGet、HttpPost、UrlEncodedFormEntity、Cookie/302 手动重定向模拟登录与 HttpPut),明确说明其在 Android 6.0(API 23)被移除的历史背景与 OkHttp/HttpURLConnection 迁移路径。
Apache HttpClient 定位、基本流程与历史移除说明
Apache `HttpClient` 是早期 Android 内置的另一套 HTTP 客户端封装,仅负责发送 HTTP 请求与接收原始响应(不执行页面脚本、不渲染 HTML,常与 Jsoup 等解析器配合提取网页数据)。典型四步流程为:创建 `DefaultHttpClient` 实例 → 构造 `HttpGet`/`HttpPost`/`HttpPut` 请求对象 → 调用 `httpClient.execute(request)` 获取 `HttpResponse` → 检查状态码 `getStatusLine().getStatusCode() == 200` 并用 `EntityUtils.toString(entity, "UTF-8")` 读取内容。必须特别注明:Google 在 Android 5.1(API 22)将其标记为废弃,并在 Android 6.0(API 23)中从默认 SDK 彻底移除;维护老代码时虽可临时声明 `useLibrary 'org.apache.http.legacy'`,但新项目应一律采用 OkHttp、Retrofit 或标准 `HttpURLConnection`。
HttpGet 参数编码与 HttpPost 表单提交
发送不带参 GET 请求时直接将 URL 传入 `new HttpGet(url)` 并在子线程执行、经 `Handler` 回传 UI 即可;若包含查询参数,则把参数装入 `List<BasicNameValuePair>`,经 `URLEncodedUtils.format(params, "UTF-8")` 编码后以 `?` 拼接到 URL 尾部。发送 POST 请求则构造 `HttpPost(url)`,将 `NameValuePair` 列表封装为 `new UrlEncodedFormEntity(params, "UTF-8")` 并通过 `httpPost.setEntity(entity)` 挂载后执行。
三步模拟登录(Cookie、表单隐藏域与 302 手动重定向)
抓取需要登录态的传统服务端页面(如教务系统)通常包含三步交互:第一步先发 `GET` 请求加载登录页,提取响应头 `Set-Cookie` 及页面中的隐藏状态字段(如 `__VIEWSTATE`);第二步构造 `HttpPost`,关闭自动重定向(`ClientPNames.HANDLE_REDIRECTS = false`),携带 `Cookie`、`Referer`、`User-Agent` 与表单字段提交登录并捕获 `302` 响应的 `Location` 头;第三步携带同一 `Cookie` 与 `Referer` 向 `Location` 目标发起 `GET` 请求即可拿到登录后的主页面 HTML。本站本地回环服务端完整复现并验证了这三步会话链路。
使用 HttpPut 提交更新与现代迁移对照
发送 `PUT` 请求与 `POST` 类似:实例化 `HttpPut(url)`、通过 `setHeader("Cookie", cookie)` 附加会话凭证并设置 `UrlEncodedFormEntity`,执行后从 `HttpEntity` 解析服务端返回的 JSON 状态码。尽管本节保留 `HttpClient` 的完整知识脉络以便读懂遗留项目,工程落地中应按 API 23+ 规范直接改写为 OkHttp(自带连接池、HTTP/2、透明压缩与拦截器链)或 Retrofit。
运行本地回环 HttpClient GET/POST/三步模拟登录(Cookie+302)/PUT 与 API 23 移除策略验证
展开查看收起
"""Offline Android legacy HttpClient workflow & API 23 removal verifier (Ch 88: tutorial-httpclient)."""
from __future__ import annotations
import http.client
import json
import re
import sys
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"
COOKIE_VAL = "ASP.NET_SessionId=legacy9988"
VIEWSTATE_TOKEN = "dDwtMTIzNDU2Nzg5Ozs+"
class LegacyPortalHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, format: str, *args) -> None:
return
def _reply(self, code: int, body: bytes, ctype: str = "text/html; charset=utf-8", extra: dict | None = None):
self.send_response(code)
self.send_header("Content-Type", ctype)
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 == "/query":
q = urllib.parse.parse_qs(parsed.query)
self._reply(200, json.dumps({k: v[0] for k, v in q.items()}, ensure_ascii=False).encode("utf-8"), "application/json")
elif parsed.path == "/login":
html_page = f'<form><input name="__VIEWSTATE" value="{VIEWSTATE_TOKEN}"/></form>'
self._reply(200, html_page.encode("utf-8"), extra={"Set-Cookie": f"{COOKIE_VAL}; path=/"})
elif parsed.path == "/main":
if COOKIE_VAL in self.headers.get("Cookie", "") and self.headers.get("Referer", "").endswith("/login"):
self._reply(200, "<html><body>课表主页:数据结构与算法</body></html>".encode("utf-8"))
else:
self._reply(403, b"forbidden")
else:
self._reply(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 == "/echo":
self._reply(200, json.dumps({k: v[0] for k, v in form.items()}, ensure_ascii=False).encode("utf-8"), "application/json")
elif self.path == "/login":
if (
COOKIE_VAL in self.headers.get("Cookie", "")
and form.get("__VIEWSTATE") == [VIEWSTATE_TOKEN]
and form.get("txtUserName") == ["stu01"]
):
self._reply(302, b"", extra={"Location": "/main"})
else:
self._reply(200, b"login_failed")
else:
self._reply(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)
if COOKIE_VAL in self.headers.get("Cookie", "") and form.get("activation_code") == ["ACT-2025"]:
self._reply(200, json.dumps({"status_code": "200", "plate": form.get("license_plate", [""])[0]}).encode("utf-8"), "application/json")
else:
self._reply(401, json.dumps({"status_code": "401"}).encode("utf-8"), "application/json")
def main() -> None:
cases = []
server = ThreadingHTTPServer(("127.0.0.1", 0), LegacyPortalHandler)
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: HttpGet with URLEncodedUtils-style UTF-8 query params
qs = urllib.parse.urlencode([("user", "开发同学"), ("pawd", "123")])
conn.request("GET", f"/query?{qs}")
r1 = conn.getresponse()
p1 = json.loads(r1.read().decode("utf-8"))
actual1 = {"status": r1.status, "params": p1}
expected1 = {"status": 200, "params": {"user": "开发同学", "pawd": "123"}}
cases.append({
"name": "httpclient_get_encoded_params",
"summary": "Verify URL-encoded GET query parameter assembly and UTF-8 server decoding.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: HttpPost with UrlEncodedFormEntity body
form_body = urllib.parse.urlencode([("user", "测试账号"), ("pawd", "123")]).encode("utf-8")
conn.request("POST", "/echo", body=form_body, headers={"Content-Type": "application/x-www-form-urlencoded"})
r2 = conn.getresponse()
p2 = json.loads(r2.read().decode("utf-8"))
actual2 = {"status": r2.status, "echo": p2}
expected2 = {"status": 200, "echo": {"user": "测试账号", "pawd": "123"}}
cases.append({
"name": "httpclient_post_form_entity",
"summary": "Verify POST form submission equivalent to UrlEncodedFormEntity with UTF-8 encoding.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: 3-step simulated login (GET cookie + __VIEWSTATE -> POST no-redirect 302 -> GET Location)
conn.request("GET", "/login")
r3a = conn.getresponse()
login_html = r3a.read().decode("utf-8")
cookie = r3a.getheader("Set-Cookie", "").split(";", 1)[0]
m = re.search(r'name="__VIEWSTATE"\s+value="([^"]+)"', login_html)
viewstate = m.group(1) if m else ""
login_payload = urllib.parse.urlencode({
"__VIEWSTATE": viewstate,
"txtUserName": "stu01",
"TextBox2": "pwd99",
}).encode("utf-8")
conn.request(
"POST",
"/login",
body=login_payload,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Cookie": cookie,
"Referer": f"http://127.0.0.1:{port}/login",
},
)
r3b = conn.getresponse()
r3b.read()
loc = r3b.getheader("Location")
conn.request(
"GET",
loc,
headers={"Cookie": cookie, "Referer": f"http://127.0.0.1:{port}/login"},
)
r3c = conn.getresponse()
main_html = r3c.read().decode("utf-8")
actual3 = {
"step1_cookie": cookie,
"step1_viewstate_extracted": viewstate == VIEWSTATE_TOKEN,
"step2_status_no_auto_redirect": r3b.status,
"step2_location": loc,
"step3_status": r3c.status,
"step3_has_schedule": "数据结构与算法" in main_html,
}
expected3 = {
"step1_cookie": COOKIE_VAL,
"step1_viewstate_extracted": True,
"step2_status_no_auto_redirect": 302,
"step2_location": "/main",
"step3_status": 200,
"step3_has_schedule": True,
}
cases.append({
"name": "simulated_login_cookie_redirect_flow",
"summary": "Verify 3-step GET cookie/viewstate -> POST 302 Location (manual redirect) -> authenticated GET.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: HttpPut with Cookie & JSON status_code parsing + API 23 removal matrix
put_body = urllib.parse.urlencode({"activation_code": "ACT-2025", "license_plate": "粤B88888"}).encode("utf-8")
conn.request(
"PUT",
"/activate",
body=put_body,
headers={"Content-Type": "application/x-www-form-urlencoded", "Cookie": cookie},
)
r4 = conn.getresponse()
j4 = json.loads(r4.read().decode("utf-8"))
conn.close()
def sdk_client_status(api_level: int) -> str:
if api_level < 22:
return "bundled_legacy"
if api_level == 22:
return "deprecated"
return "removed_use_okhttp_or_httpurlconnection"
actual4 = {
"put_status_code": int(j4["status_code"]),
"plate": j4["plate"],
"api22": sdk_client_status(22),
"api23_plus": sdk_client_status(23),
}
expected4 = {
"put_status_code": 200,
"plate": "粤B88888",
"api22": "deprecated",
"api23_plus": "removed_use_okhttp_or_httpurlconnection",
}
cases.append({
"name": "httpclient_put_and_api23_deprecation",
"summary": "Verify authenticated PUT JSON response and Apache HttpClient removal policy from Android 6.0 (API 23).",
"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())
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
部分系统在登录 302 跳转时同时下发或校验新的 Set-Cookie 与 Referer;关闭自动重定向便于客户端精确捕获 302 状态码、提取 Location 路径并显式附带正确的 Cookie 与 Referer 头。