[英]Unable to send `multipart/form-data` request with python requests module
I have Java spring server that requires the Content-Type
of the requests being sent to the server to be multipart/form-data
. 我有Java spring服务器,它要求发送到服务器的请求的
Content-Type
是multipart/form-data
。
I can correctly send requests to the server with postman: 我可以使用邮递员将请求正确发送到服务器:
However, I got The current request is not a multipart request
error when trying to send the request with requests
module in python3. 但是,我尝试在python3中使用
requests
模块发送请求时The current request is not a multipart request
错误。
My python code is: 我的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)
If I add 'Content-Type': 'multipart/form-data'
to the header of the request, the error message then becomes Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
如果我将
'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
Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
. Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
。
How can I make the same request as postman sends with python? 如何发出与邮递员使用python发送的相同请求?
requests
's author thinks this situation is not pythonic, so requests
doesn't support this usage natively. requests
的作者认为这种情况不是pythonic的,因此requests
本身不支持这种用法。
You need to use requests_toolbelt
which is an extension maintained by members of the requests core development team, doc , example: 您需要使用
requests_toolbelt
,它是由请求核心开发团队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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.