Python请求http错误600

时间:2017-11-06 15:27:25

标签: python rest http

我尝试将文件上传到远程网站,使用CURL脚本,它运作良好

curl -X POST -H "Content-Type: multipart/form-data" -H "Authorization: Basic cWERF0ZWNoQXBpOmYxZDhmNzJkNDAwNGRjNzZlMTU0NjU4MTQwGRNzc4NTjM0" -F "data=@file.dat" http://url/rest/files/upload

但是当我尝试使用Python请求时,我遇到了这个错误:

600 org.jvnet.mimepull.MIMEParsingException:缺少起始边界

我的python代码:

import requests
headers = {
    'Content-Type': 'multipart/form-data',
    'Authorization': 'Basic cWERF0ZWNoQXBpOmYxZDhmNzJkNDAwNGRjNzZlMTU0NjU4MTQwGRNzc4NTjM0',}     
files = {'file.dat':open('file.dat','rb')}
response = requests.post('http://url/rest/files/upload',headers=headers,files=files)
print response.text

1 个答案:

答案 0 :(得分:0)

您必须避免'Content-Type'词典中的headers。这条路:

import requests
headers = {'Authorization': 'Basic cWERF0ZWNoQXBpOmYxZDhmNzJkNDAwNGRjNzZlMTU0NjU4MTQwGRNzc4NTjM0',}     
files = {'file.dat':open('file.dat','rb')}
response = requests.post('http://url/rest/files/upload',headers=headers,files=files)

在这种特殊情况下(如果指定了参数files),库requests会自行添加Content-Type: multipart/form-data,但最后会添加边界的规范。然后标题看起来像这样:

Content-Type: multipart/form-data; boundary=e8c4b746efb54e2f9ae9412a4402714b

通过将'Content-Type': 'multipart/form-data'添加到headers参数,将删除边界。