🌐 Python 标准库 - http 模块详解( 构建与处理 HTTP 协议)
📌 模块概览
Python 提供了多个 http 相关模块,支持基本的 HTTP 协议处理,常用于开发 Web 服务与测试:
| 子模块 | 用途 |
|---|---|
http.server | 快速启动一个 HTTP 服务 |
http.client | 构建 HTTP 客户端 |
http.cookies | 处理 HTTP Cookies |
http.cookiejar | 管理 Cookie 的存储与处理(配合 urllib 使用) |
🚀 1️⃣ 启动本地 HTTP 服务(开发调试用)
from http.server import SimpleHTTPRequestHandler, HTTPServer
地址 = ("", 8000)
服务 = HTTPServer(地址, SimpleHTTPRequestHandler)
print("服务器启动:http://localhost:8000")
服务.serve_forever()
启动后浏览器访问 http://localhost:8000
🛠️ 2️⃣ 自定义 HTTP 响应(继承 Handler)
from http.server import BaseHTTPRequestHandler, HTTPServer
class 我的处理器(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send—_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(b"你好,世界!")
地址 = ("", 8080)
服务 = HTTPServer(地址, 我的处理器)
print("自定义服务器运行中:http://localhost:8080")
服务.serve_forever()
🌐 3️⃣ 使用 http.client 发起请求
import http.client
连接 = http.client.HTTPSConnection("httpbin.org")
连接.request("GET", "/get")
响应 = 连接.getresponse()
print("状态码:", 响应.status)
print("响应内容:", 响应.read().decode())
🍪 4️⃣ 处理 Cookies(http.cookies)
from http import cookies
C = cookies.SimpleCookie()
C["用户名"] = "alice"
C["用户名"]["path"] = "/"
print(C.output())
📦 5️⃣ 配合 urllib 管理 Cookie(http.cookiejar)
import urllib.request
import http.cookiejar
cookie_jar = http.cookiejar.CookieJar()
处理器 = urllib.request.HTTPCookieProcessor(cookie_jar)
打开器 = urllib.request.build_opener(处理器)
响应 = 打开器.open("[https://httpbin.org/cookies/set?mycookie=test](https://httpbin.org/cookies/set?mycookie=test)")
print("Cookie 已存储数量:", len(cookie_jar))
✅ 小结
| 模块名 | 功能说明 |
|---|---|
http.server | 启动本地 HTTP 测试服务 |
http.client | 构建 GET/POST 请求客户端 |
http.cookies | 创建和解析 Cookie |
http.cookiejar | 自动管理 Cookie(配合 urllib) |