【问题标题】:Issue sending multipart/form-data发送多部分/表单数据的问题
【发布时间】:2020-11-19 15:28:56
【问题描述】:

我正在尝试使用 BIMTrack 的 REST API 来发布图像。为此,API 要求我在图像之前发送一个 json 文件,本质上需要 multipart/form-data。

json 填充失败后将遇到错误代码:415 和错误消息:The content-type of the first file of the request must be application\json

我已使用 Postman & Fiddler 的 Web 调试代理成功发出此帖子请求,但无法在 python 请求中重复我的成功。

Python 代码(这不起作用):

image = r"C:\Users\aflemming\Desktop\Images\DBMICon.png"
jsonFile = r"C:\Users\aflemming\source\repos\IfcOpenShell\IfcOpenShell\BIM\myjson.json"

headers = {'Authorization' : 'Bearer <MyToken>'}

files = {
    'Json': (None, open(jsonFile, 'rb'), 'application/json'),
    'Image': (None, open(image, 'rb'), 'image/png')
}

r = requests.post(https://api.bimtrackapp.co/v3/hubs/07La7cOZ/projects/20767/issues/3161484/viewpoints, files=files, headers=headers)

Fiddler 原始请求(可行):

User-Agent:Fiddler Everywhere
Authorization:Bearer eb5e3983a7546dad76067418ff93175ef42b816dd57f78f54101f0b63862542e
Host:api.bimtrackapp.co
Content-Length:11322
Content-Type:multipart/form-data;boundary=-------------------------acebdf13572468

---------------------------acebdf13572468
Content-Disposition: form-data; name="description" 
the_text_is_here
---------------------------acebdf13572468
Content-Disposition: form-data; name="jsonfile"; filename="myjson.json"
Content-Type: application/json

<@INCLUDE *C:\Users\aflemming\source\repos\IfcOpenShell\IfcOpenShell\BIM\myjson.json*@>
---------------------------acebdf13572468
Content-Disposition: form-data; name="image"; filename="DBMICon.png"
Content-Type: image/png

<@INCLUDE *C:\Users\aflemming\Desktop\Images\DBMICon.png*@>
---------------------------acebdf13572468--

邮递员请求(这也有效):

BIMTrack 的 REST API:https://api.bimtrackapp.co/swagger/ui/index

我很乐意在需要时提供更多信息。

【问题讨论】:

  • 尝试使用发送下方的代码按钮直接从邮递员获取代码并选择 python 请求。这可能会有所帮助
  • 谢谢 Yash,我以前试过这个,但无济于事。然而,在用一些新知识再次尝试之后,它现在可以工作了!万岁!谢谢你提醒我再试一次。

标签: python http python-requests multipartform-data


【解决方案1】:

我通过更改请求方法(在 requests.post 上使用 requests.request)并设置 verify=False 参数找到了解决方案。

似乎请求遇到了SSLCertVerificationError,绕过证书解决了这个问题。

最终代码:

image = r"C:\Users\aflemming\Desktop\Images\DBMICon.png"
jsonFile = r"C:\Users\aflemming\source\repos\IfcOpenShell\IfcOpenShell\BIM\myjson.json"
url = "https://api.bimtrackapp.co/v3/hubs/07La7cOZ/projects/20767/issues/3161484/viewpoints"

files = [
    ('Json', ('Json2', open(jsonFile,'rb'), 'application/json')),
    ('Image', ('Image2', open(image,'rb'), 'image/png'))
]

headers = {
    'Authorization': 'Bearer <MyToken>'
}

response = requests.request("POST", url, headers=headers, files = files, verify=False)

【讨论】:

    猜你喜欢
    • 2019-11-19
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2014-01-10
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    相关资源
    最近更新 更多