Python requests.post() 方法:Form 表单与 JSON 请求的参数配置详解
一、核心区别对比
特性 | Form 表单 (data ) | JSON 载荷 (json ) |
---|---|---|
参数名 | data | json |
Content-Type | application/x-www-form-urlencoded | application/json |
数据格式 | 键值对(扁平结构) | 任意 JSON(支持嵌套) |
编码方式 | URL 编码 | JSON 序列化 |
典型场景 | HTML 表单提交 | REST API 交互 |
二、Form 表单提交详解
1. 基本用法
import requests
url = "https://example.com/login"
form_data = {
"username": "user123",
"password": "pass456"
}
response = requests.post(url, data=form_data)
- 技术要点
1.自动设置Content-Type为表单模式
2.数据会被编码为key=value$形式
3. 适合模式传统的html表单的提交
三、JSON请求提交实战
基础案例
payload = {
"user": {
"name": "Alice",
"profile": {
"age": 25,
"vip": True
},
"tags": ["python", "web"]
}
}
response = requests.post(url, json=payload)
技术要点
- 自动设置JSON内容类型
- 支持任意嵌套数据结构
- 返回数据通常为JSON格式
四、常见问题的解决方案
问题1:400 Bad Request错误
response = requests.post(url, data=json_data)
# 正确方式(自动处理编码和头信息)
response = requests.post(url, json=json_data)
问题2:混合提交文件+JSON
data = {'info': json.dumps({'desc': '测试文件'})}
response = requests.post(url, files=files, data=data)
问题3:自定义请求头
"X-API-Key": "your_api_key",
"Accept": "application/vnd.api+json"
}
response = requests.post(url, json=data, headers=headers)
五、高级调试技巧
请求日志记录
logging.basicConfig(level=logging.DEBUG)
response = requests.post(url, json=data)
异常处理模板
response = requests.post(url, json=data, timeout=5)
response.raise_for_status()
result = response.json()
except requests.exceptions.RequestException as e:
print(f"请求失败: {str(e)}")
if hasattr(e, 'response'):
print("错误响应:", e.response.text[:200])