无法使用python requests modu发送“multipart/formdata”请求

2024-06-28 20:50:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个javaspring服务器,它要求发送到服务器的请求的Content-Type是{}。在

我可以通过邮递员向服务器正确发送请求:

enter image description here

enter image description here

但是,当我试图用python3中的requests模块发送请求时,遇到了The current request is not a multipart request错误。在

我的python代码是:

import requests

headers = {
  'Authorization': 'Bearer auth_token'
}

data = {
  'myKey': 'myValue'
}

response = requests.post('http://127.0.0.1:8080/apiUrl', data=data, headers=headers)
print(response.text)

如果我将'Content-Type': 'multipart/form-data'添加到请求的头中,那么错误消息就会变成Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found。在

我如何才能发出与postman使用python发送的请求相同的请求?在


Tags: 服务器邮递员dataisresponserequesttype错误
1条回答
网友
1楼 · 发布于 2024-06-28 20:50:42

requests的作者认为这种情况不是python的,因此requests本机不支持这种用法。在

您需要使用requests_toolbelt,它是由requests核心开发团队成员维护的扩展doc,例如:

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

m = MultipartEncoder(
    fields={'field0': 'value', 'field1': 'value',
            'field2': ('filename', open('file.py', 'rb'), 'text/plain')}
    )

r = requests.post('http://httpbin.org/post', data=m,
                  headers={'Content-Type': m.content_type})

相关问题 更多 >