httpx
是 Python 中一个功能强大的 HTTP 客户端库,支持同步和异步请求、HTTP/2、连接池等功能。以下是 httpx
的常用方法及实际示例:
1. 安装
pip install httpx
2. 核心方法及示例
(1) 同步请求
httpx.get()
: 发送 GET 请求httpx.post()
: 发送 POST 请求httpx.put()
: 发送 PUT 请求httpx.delete()
: 发送 DELETE 请求httpx.request()
: 通用请求方法
示例:同步 GET 请求
import httpx
response = httpx.get("https://httpbin.org/get")
print(response.status_code) # 200
print(response.text) # 返回的文本内容
print(response.json()) # 解析 JSON 响应
(2) 使用 Client
类
通过 httpx.Client()
创建客户端实例,支持连接池和复用配置(如 headers、超时等)。
示例:使用 Client
with httpx.Client(headers={"User-Agent": "MyApp"}, timeout=10) as client:
response = client.get("https://httpbin.org/get")
print(response.json())
# 发送 POST 表单数据
response = client.post(
"https://httpbin.org/post",
data={"key": "value"}
)
(3) 异步请求
使用 AsyncClient
发送异步请求(需配合 asyncio
)。
示例:异步 GET 请求
import httpx
import asyncio
async def fetch_data():
async with httpx.AsyncClient() as client:
response = await client.get("https://httpbin.org/get")
print(response.json())
asyncio.run(fetch_data())
(4) 处理响应对象
响应对象(Response
)的常用属性和方法:
response.status_code
: 状态码(如 200、404)response.headers
: 响应头(字典格式)response.text
: 文本格式的响应内容response.json()
: 解析 JSON 响应response.raise_for_status()
: 如果状态码为 4xx/5xx,抛出异常
示例:处理错误状态码
response = httpx.get("https://httpbin.org/status/404")
try:
response.raise_for_status() # 抛出 httpx.HTTPStatusError
except httpx.HTTPStatusError as e:
print(f"错误: {e}")
(5) 文件上传
使用 files
参数上传文件。
示例:上传文件
files = {"file": open("example.txt", "rb")}
response = httpx.post("https://httpbin.org/post", files=files)
print(response.json())
(6) 设置超时与认证
- 超时:通过
timeout
参数设置。 - 认证:通过
auth
参数设置(如基本认证)。
示例:超时与认证
# 设置超时为 5 秒
response = httpx.get("https://httpbin.org/delay/3", timeout=5)
# 基本认证
auth = ("user", "pass")
response = httpx.get("https://httpbin.org/basic-auth/user/pass", auth=auth)
(7) 启用 HTTP/2
需安装 httpx[http2]
并显式启用。
示例:HTTP/2 请求
client = httpx.Client(http2=True)
response = client.get("https://httpbin.org/get")
print(response.http_version) # 输出 "HTTP/2"
3. 高级功能
-
流式响应:使用
stream()
处理大文件。with httpx.stream("GET", "https://httpbin.org/stream/10") as response: for chunk in response.iter_bytes(): print(chunk)
-
代理:通过
proxies
参数配置。proxies = {"http://": "http://proxy.example.com"} response = httpx.get("http://httpbin.org/ip", proxies=proxies)
4. 总结
httpx
的主要优势:
- 支持同步和异步请求。
- 兼容 HTTP/1.1 和 HTTP/2。
- 提供类型注解和现代化 API。
- 丰富的功能(如文件上传、代理、连接池)。
通过上述示例,可以快速上手 httpx
进行 HTTP 请求操作。