在Python中处理HTTP响应,核心是使用requests库。收到响应后,你主要和Response对象打交道。
1. 基本处理:状态码、头部和内容
import requests
resp = requests.get('https://api.example.com/data')
# 检查状态码
if resp.status_code == 200:
print('请求成功')
else:
print(f'请求失败,状态码: {resp.status_code}')
# 获取响应头部 (字典)
headers = resp.headers
print(headers.get('Content-Type'))
# 获取响应内容
# 文本内容
text_content = resp.text
# 二进制内容
binary_content = resp.content
# 对于JSON响应,直接解析为字典/列表
json_data = resp.json()
2. 处理编码和原始数据
# 查看/设置编码
print(resp.encoding)
resp.encoding = 'utf-8' # 如果自动检测不对,手动设置
# 获取原始套接字响应 (用于流式或低级操作)
raw_response = resp.raw
3. 处理重定向和超时
# 禁用重定向
resp = requests.get(url, allow_redirects=False)
# 设置超时 (连接超时和读取超时)
resp = requests.get(url, timeout=(3.05, 27))
4. 错误处理
try:
resp = requests.get(url, timeout=5)
resp.raise_for_status() # 如果状态码不是200,抛出HTTPError
data = resp.json()
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.HTTPError as e:
print(f"HTTP错误: {e}")
except requests.exceptions.RequestException as e:
print(f"请求异常: {e}")
except ValueError: # json解析失败
print("响应不是有效的JSON")
5. 流式处理大响应
# 对于大文件,使用流式模式
resp = requests.get(url, stream=True)
with open('large_file.zip', 'wb') as f:
for chunk in resp.iter_content(chunk_size=8192):
f.write(chunk)
6. 处理Cookies和Session
# 单个请求的cookies
cookies = resp.cookies
# 使用Session保持cookies和连接
session = requests.Session()
session.get('https://example.com/login') # 获取cookies
resp = session.get('https://example.com/dashboard') # 自动携带cookies
简单总结:用requests库,根据响应内容类型选.text、.json()或.content,做好错误处理。