无法通过python请求模块发送`multipart / form-data`请求

时间:2018-06-26 03:31:46

标签: java python spring python-requests

我有一个Java spring服务器,它要求发送到服务器的请求中的Content-Typemultipart/form-data

我可以使用邮递员将请求正确发送到服务器:

enter image description here

enter image description here

但是,在python3中尝试通过The current request is not a multipart request模块发送请求时遇到了requests错误。

我的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

如何发出与邮递员使用python发送的相同请求?

1 个答案:

答案 0 :(得分:3)

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

您需要使用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})
相关问题