1.'content-type':'application/x-www-form-urlencoded'
- data参数提交
<str>
文本或<dict>
字典都可以 - headers为空时,data提交
content-type
默认也是application/x-www-form-urlencoded
requests.post(url,headers={'content-type':'application/x-www-form-urlencoded'},data='f=10')
requests.post(url,headers={'content-type':'application/x-www-form-urlencoded'},data={'f':10})
2. 'content-type':'application/json'
- data参数提交
<str>
或json参数提交<dict>
- data参数提交
<str>
:注意str必须是json.dumps(<dict>)
转换的标准的json字符串,而非str(<dict>)
,这两者并不完全等同。 - json参数提交
<dict>
:模块会自动将dict转换为json提交。
requests.post(url,headers={'content-type':'application/json'},data=json.dumps({'f':10}))
requests.post(url,headers={'content-type':'application/json'},json={'f':10})
3. 'content-type':'text/xml'
- data参数提交
<bytes>
- 通常用于上传xml格式文本等;将文本
<str>.encode("utf-8")
编码为bytes类型上传
requests.post(url,headers={'content-type':'text/xml'},data='<xml......>'.encode("utf-8"))
4. 'content-type':'multipart/formdata'
- files参数提交
<dict>
- 用于上传文件;通常Content-Type中除了
Content-Type: multipart/form-data
,还有个boundary=随机字符串
,该项的作用是当作提交内容的分隔符,构造files时用不到可以忽略。
举个例子:
Request Headers
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryzf3ou2ZJHNJq9V0N
------------------------------------------------------------
FormData
file: (binary)
else1: xxx1
else2: xxx2
------------------------------------------------------------
FormData view source
------WebKitFormBoundaryzf3ou2ZJHNJq9V0N
Content-Disposition: form-data; name="file"; filename="test.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryzf3ou2ZJHNJq9V0N
Content-Disposition: form-data; name="else1"
xxx1
------WebKitFormBoundaryzf3ou2ZJHNJq9V0N
Content-Disposition: form-data; name="else2"
xxx2
------WebKitFormBoundaryzf3ou2ZJHNJq9V0N--
可以整理如下方式提交
files = {
"file":("test.jpg", open(r"D:\test\test.jpg",'rb')),
"else1": (None,"xxx1"),
"else2": (None,"xxx2")
}
r = requests.post(url,files=files)