【发布时间】:2020-04-29 13:16:13
【问题描述】:
想在我现有的 API 上调用 Post 方法,该 API 可以与 PostMan 一起正常工作,但现在我想将正文内容作为文件类型传递。
当前,当我在 request.post 中添加标头时,它会抛出 400 错误请求异常,但是当我删除标头时,它会给我 415 媒体类型,我无法理解,谁能帮我解决这个问题。
这里提到了我的工作代码:
import os
import logging
import requests
from requests.auth import HTTPBasicAuth
config_directory = 'my-laptp-location\where-i-have\all-mt-files'
url = 'http://localhost:8080/api/v1/update'
usr = 'user'
passwd = 'pass'
for fileName in os.listdir(config_directory):
print('Processing file: ', fileName)
headers={'Content-type':'application/json', 'Accept':'application/json'}
abs_path = os.path.abspath(os.path.join(config_directory, fileName))
# files = {'file': (abs_path, open(abs_path, 'rb'), 'application/json', {'Expires': '0'})}
# I tried the above as well but It also throw media type exception
with open(abs_path, 'rb') as f:
r = requests.post(calling_url, files={abs_path: f}, auth=HTTPBasicAuth(usr,passwd),headers=headers)
print(r.status_code)
我的文件,如果我执行 vi abs_path:
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
}
它只是简单的 JSON,不是数组,没有嵌套。
【问题讨论】:
-
您是否将正确的
'Accept'传递给您的标题? -
Content-Type标头需要为multipart/form-data以进行文件上传 -
您应该为
config_directory使用r类型文字,即:config_directory = r'my-laptp-location\where-i-have\all-mt-files',因为\a是'\x07'(警报)而不是反斜杠后跟'a'。 -
我尝试使用这两个评论从标题中删除 Accept 并按照@RishiDev 的建议添加了 multipart/form-data 但仍然有 415 作为不受支持的媒体类型,我已经更新了我的输入文件
-
我已经尝试了互联网上的所有内容,但没有按预期工作 - 最后它说“不支持的媒体类型”415。不知道从这里做什么?
标签: python python-3.x python-requests