requests.post(url,json,headers,timeout)函数参数json、data、parameter的区别
这是一个非常常见的 requests 库使用问题。下面详细解释一下这三个参数的区别和使用场景:
1.json参数
使用场景:当你要发送 JSON 格式的数据到服务器时
特点:
自动将 Python 对象(dict、list 等)序列化为 JSON 字符串
自动设置
Content-Type为application/json适用于 RESTful API
import requests payload = { "name": "John", "age": 30, "hobbies": ["reading", "swimming"] } # 推荐方式 - 使用 json 参数 response = requests.post( url="https://api.example.com/users", json=payload, # 自动序列化为 JSON headers=headers, timeout=30 ) # 等价于手动处理: # headers['Content-Type'] = 'application/json' # data = json.dumps(payload) # requests.post(url, data=data, headers=headers)2.data参数
使用场景:
发送表单数据(application/x-www-form-urlencoded)
发送 multipart 表单数据(文件上传)
发送原始字符串数据
# 场景1:表单数据 form_data = { "username": "john", "password": "secret" } response = requests.post( url="https://example.com/login", data=form_data, # 自动编码为表单格式 headers=headers ) # 场景2:文件上传 files = {'file': open('image.jpg', 'rb')} response = requests.post( url="https://example.com/upload", files=files, data={'description': 'My image'} # 其他表单字段 ) # 场景3:原始字符串 xml_data = "<user><name>John</name></user>" response = requests.post( url="https://example.com/api", data=xml_data, headers={'Content-Type': 'application/xml'} )3.params参数
使用场景:用于 URL 查询字符串参数(GET 请求的参数)
特点:
参数会附加在 URL 的
?后面只用于 GET 请求或需要在 URL 中传递参数的情况
query_params = { "page": 1, "limit": 10, "search": "python" } response = requests.get( url="https://api.example.com/articles", params=query_params, # 添加到 URL: ?page=1&limit=10&search=python headers=headers )总结对比
| 参数 | 用途 | Content-Type | 位置 |
|---|---|---|---|
json | 发送 JSON 数据 | application/json | 请求体 |
data | 发送表单数据/原始数据 | 多种类型 | 请求体 |
params | URL 查询参数 | - | URL 中 |
实际使用建议
import requests # ✅ 推荐:RESTful API 使用 json api_response = requests.post( "https://api.example.com/users", json={"name": "John", "age": 30}, headers={"Authorization": "Bearer token"} ) # ✅ 推荐:表单提交使用 data form_response = requests.post( "https://example.com/login", data={"username": "john", "password": "secret"} ) # ✅ 推荐:GET 请求参数使用 params search_response = requests.get( "https://api.example.com/search", params={"q": "python", "page": 1} ) # ❌ 避免:不要混淆使用 # 错误:用 data 发送 dict 到期望 JSON 的 API # requests.post(url, data=dict_data) # 可能出错 # 正确:明确指定数据格式 requests.post(url, json=dict_data) # 对于 JSON API requests.post(url, data=dict_data) # 对于表单接口简单记忆:
API 交互→ 用
json表单提交→ 用
dataURL 参数→ 用
params文件上传→ 用
files+data