Bri*_*ian 0 python java spring python-requests
我有 Java spring 服务器,它要求Content-Type发送到服务器的请求为multipart/form-data.
我可以使用邮递员正确地向服务器发送请求:
但是,The current request is not a multipart request尝试requests在python3中使用模块发送请求时出错。
我的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)
Run Code Online (Sandbox Code Playgroud)
如果我添加'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 发送的请求相同的请求?
requests的作者认为这种情况不是pythonic,所以原生requests不支持这种用法。
您需要使用requests_toolbeltwhich 是由 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})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3367 次 |
| 最近记录: |