http请求中的headers和body内容设置
1.headers
1.1 内容相关
headers = {
'Content-Type': 'application/json', # 或 'application/x-www-form-urlencoded', 'multipart/form-data'
'Content-Length': '1234', # 内容长度
'Accept': 'application/json', # 期望的返回格式
'Accept-Encoding': 'gzip, deflate', # 支持的压缩方式
'Accept-Language': 'zh-CN,zh;q=0.9' # 支持的语言
}
其中content-type对应需要传输的内容格式:
- application/json: { ‘name’:’edward’, ‘age’:’25’ }
- application/x-www-form-urlencoded: name=edward&age=25
1.2 认证相关
headers = {
'Authorization': 'Bearer <token>', # JWT认证
'Cookie': 'session=abc123', # Cookie认证
'X-API-Key': '<api_key>', # API密钥
'token': '<your_token>' # 自定义token
}
1.3 请求源信息
headers = {
'User-Agent': 'Mozilla/5.0...', # 客户端信息
'Origin': 'https://example.com', # 请求来源
'Referer': 'https://example.com/page', # 请求的前一页面
'X-Requested-With': 'XMLHttpRequest' # AJAX请求标识
}
2. body
payload里的数据格式要和headers里指明的Content-Type一致。
2.1 json格式
python中的使用:
payload = json.dumps({
"username": "test",
"password": "123456",
"data": {
"key1": "value1",
"key2": "value2"
}
})
2.2 表单格式
payload = {
'username': 'test',
'password': '123456',
'remember': 'true'
}
# 使用 urllib.parse.urlencode(payload) 进行编码