Python 请求在发布数据时出现 415 错误

新手上路,请多包涵

将数据发布到服务器时出现 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)

原文由 Mitra Mishra 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
1 个回答

根据 MDN Web 文档

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)

原文由 Giorgos Myrianthous 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题