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

Mit*_*hra 6 python python-requests http-status-code-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)
Run Code Online (Sandbox Code Playgroud)

Gio*_*ous 16

根据MDN 网络文档

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

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

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

headers={
    'Content-type':'application/json', 
    'Accept':'application/json'
}
Run Code Online (Sandbox Code Playgroud)

并包括headers在您的POST请求中:

r = requests.post(
    url, 
    auth=HTTPBasicAuth('shany.ka', 'shanky1213'),
    json=data,
    headers=headers
)
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩


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)
Run Code Online (Sandbox Code Playgroud)

  • 作为Python的新手,我一直对json x data参数的差异感到困惑,在使用data参数发送正文时我不断收到415。使用 json 参数解决了该问题,您甚至不需要发送内容类型标头。 (2认同)