【问题标题】:Python request gives 415 error while post dataPython 请求在发布数据时出现 415 错误
【发布时间】:2018-09-07 06:48:57
【问题描述】:

我在将数据发布到服务器时收到 415 错误。这是我的代码我该如何解决这个问题。提前致谢!

import requests
import json
from requests.auth import HTTPBasicAuth
#headers = {'content-type':'application/javascript'}
#headers={'content-type':'application/json', 'Accept':'application/json'}
url = 'http://IPadress/kaaAdmin/rest/api/sendNotification'
data = {"name": "Value"}
r = requests.post(url, auth=HTTPBasicAuth('shany.ka', 'shanky1213'),json=data)
print(r.status_code)

【问题讨论】:

  • 您是否尝试取消注释 headers={'content-type':'application/json', 'Accept':'application/json'} 并在您的 POST 请求中包含标头?
  • 是的,我已经完成了,但和之前一样,响应错误 415。

标签: python python-requests http-status-code-415


【解决方案1】:

根据MDN Web Docs

HTTP 415 Unsupported Media Type 客户端错误响应代码 表示服务器拒绝接受请求,因为 有效负载格式是不受支持的格式。

格式问题可能是由于请求的指示 Content-Type 或 Content-Encoding,或作为检查的结果 直接数据。

就您而言,我认为您错过了标题。 取消注释

headers={
    'Content-type':'application/json', 
    'Accept':'application/json'
}

并在您的POST 请求中包含headers

r = requests.post(
    url, 
    auth=HTTPBasicAuth('shany.ka', 'shanky1213'),
    json=data,
    headers=headers
)

应该做的伎俩


import requests
import json
from requests.auth import HTTPBasicAuth


headers = {
    'Content-type':'application/json', 
    'Accept':'application/json'
}
url = 'http://IPadress/kaaAdmin/rest/api/sendNotification'
data = {"name": "Value"}

r = requests.post(
    url, 
    auth=HTTPBasicAuth('shany.ka', 'shanky1213'), 
    json=data, 
    headers=headers
)
print(r.status_code)

【讨论】:

  • 作为 Python 的新手,我一直对 json x 数据参数的差异感到困惑,我在使用数据参数发送正文时一直收到 415。使用 json 参数解决了这个问题,你甚至不需要发送内容类型头。
  • 我收到同样的错误并将其作为一个新问题发布在这里:stackoverflow.com/questions/67936078/… 并且解决方案也是相同的。我必须添加 data={"key,"value"} 才能使其工作,即使 data 根据文档是可选关键字。
  • 我也遇到了同样的问题。谢谢你的帮助。
【解决方案2】:

作为一种解决方法,请尝试使用 Postman 访问您的 api。当你可以在 postman 中成功点击 api 时,在 postman 中生成 python 代码(按钮在右上角)。您可以将代码复制到您的python项目中。

【讨论】:

  • Postman 实际上给了你很好的代码。我遇到了同样的问题,但我遵循了这个,然后解决了我的问题。这是一个链接,看看如何从邮递员youtube.com/watch?v=4XxcBI2uViA获取代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-03
  • 2021-05-25
  • 1970-01-01
  • 2023-03-21
  • 2020-06-30
相关资源
最近更新 更多