Python requests模块POST提交请求,不同Content-type对应的参数示例

1.'content-type':'application/x-www-form-urlencoded'

data参数提交文本或字典都可以
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参数提交或json参数提交
data参数提交:注意str必须是json.dumps()转换的标准的json字符串,而非str(),这两者并不完全等同。
json参数提交:模块会自动将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)
posted @ 2024-01-25 10:49  hanfe1  阅读(894)  评论(0编辑  收藏  举报