我正在尝试向我的网络服务器发送通知但是它显示错误401.我已经在邮递员中测试了我的API密钥并且它可以工作但是当我在python中使用它时它显示错误401或错误:unathenticated。
这是我的代码
import requests
req = requests.post('https://sampleweb.com/api/v1/devices/1/notifications',
json={ 'Authorization': 'Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9',
"notification": { "message":"hey", "level": 4}})
print(req.json())
file = open("alert_content.txt", "a")
file.write(req.text + "\n")
file.close()
我搜索并阅读了一些关于我的问题的文件,我已经解决了。这是代码。
import requests
url = "https://sampleweb.com/api/v1/devices/1/notifications"
auth = {'Authorization': 'Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ',
'content-type':'application/json'}
params = {"notification":{"message":message,"level":level}}
req = requests.post(url, headers= auth, json = params)
print(req.json())
file = open("alert_content.txt", "a")
file.write(req.text + "\n")
file.close()
授权需要内容类型和参数或参数需要采用json格式。现在它有效。