HTTPX怎么用

发布于:2025-06-23 ⋅ 阅读:(14) ⋅ 点赞:(0)

httpx 是一个功能强大的 Python HTTP 客户端库,支持 HTTP/1.1、HTTP/2 和异步请求


安装 httpx

pip install httpx
# 安装 HTTP/2 支持(可选)
pip install httpx[http2]

基础用法

1. 发送 GET 请求

import httpx

# 同步请求
response = httpx.get("https://httpbin.org/get")
print(response.status_code)  # 状态码
print(response.text)         # 响应文本

# 带参数的请求
params = {"key1": "value1", "key2": "value2"}
response = httpx.get("https://httpbin.org/get", params=params)

2. 发送 POST 请求

# 表单数据
data = {"username": "user", "password": "pass"}
response = httpx.post("https://httpbin.org/post", data=data)

# JSON 数据
json_data = {"name": "Alice", "age": 30}
response = httpx.post("https://httpbin.org/post", json=json_data)

3. 设置 Headers

headers = {"User-Agent": "MyApp/1.0", "Authorization": "Bearer token"}
response = httpx.get("https://httpbin.org/headers", headers=headers)

4. 处理响应

response = httpx.get("https://api.example.com/data")

# 常用属性
print(response.status_code)    # 200
print(response.headers)        # 响应头(字典)
print(response.text)           # 文本内容(自动解码)
print(response.content)        # 原始字节数据
print(response.json())         # 解析为 JSON(字典)

高级功能

1. 使用 Client(推荐)

复用连接,提升性能(尤其适合多次请求):

with httpx.Client() as client:
    # 统一设置超时/headers/base_url
    response1 = client.get("https://httpbin.org/get", timeout=10.0)
    response2 = client.post("https://httpbin.org/post", data={"key": "value"})

2. 异步请求

import asyncio

async def main():
    async with httpx.AsyncClient() as client:
        response = await client.get("https://httpbin.org/get")
        print(response.json())

asyncio.run(main())

3. 代理设置

proxies = {"http://": "http://10.10.1.10:8080", "https://": "https://10.10.1.10:443"}
response = httpx.get("https://example.com", proxies=proxies)

4. 超时控制

# 全局超时(连接+读取)
response = httpx.get("https://example.com", timeout=5.0)

# 分层设置
timeout = httpx.Timeout(connect=3.0, read=10.0)
response = httpx.get("https://example.com", timeout=timeout)

5. 文件上传

files = {"file": open("report.txt", "rb")}
response = httpx.post("https://httpbin.org/post", files=files)

6. SSL 验证

# 关闭证书验证(不推荐)
response = httpx.get("https://example.com", verify=False)

# 自定义 CA 证书
response = httpx.get("https://example.com", verify="/path/to/cert.pem")

错误处理

try:
    response = httpx.get("https://invalid.url", timeout=2.0)
    response.raise_for_status()  # 检查 4xx/5xx 错误
except httpx.ConnectTimeout:
    print("连接超时")
except httpx.HTTPStatusError as e:
    print(f"HTTP错误: {e.response.status_code}")
except httpx.RequestError as e:
    print(f"请求失败: {e}")

完整示例

import httpx

# 创建客户端(复用连接)
with httpx.Client(
    base_url="https://api.example.com",
    headers={"Authorization": "Bearer TOKEN"},
    timeout=10.0
) as client:
    try:
        # 获取用户数据
        response = client.get("/users/1")
        response.raise_for_status()
        user = response.json()
        print(f"用户: {user['name']}")

        # 更新用户
        update_data = {"email": "new@example.com"}
        response = client.patch("/users/1", json=update_data)
        
    except httpx.HTTPError as e:
        print(f"API 错误: {e}")

注意事项

  1. 性能:对于高频请求,使用 ClientAsyncClient 复用连接。

  2. 异步支持:异步请求需搭配 async/await 和事件循环(如 asyncio)。

  3. HTTP/2:需额外安装 httpx[http2] 并启用(Client(http2=True))。

  4. 超时设置:务必设置合理的超时时间(默认无超时)。

官方文档:https://www.python-httpx.org/

 

本文章仅供参考使用


网站公告

今日签到

点亮在社区的每一天
去签到