【问题标题】:Python Requests getting 401 errorPython 请求得到 401 错误
【发布时间】:2018-06-12 04:04:12
【问题描述】:

目前正在尝试使用 python 请求 json,但我在响应时不断收到 401 错误。当我使用 curl 时,我收到了正确的 json 数据。

我使用的卷曲:

curl -H "X-Samanage-Authorization: Bearer API_TOKEN" -H 'Accept: application/vnd.samanage.v2.1+json' -H 'Content-Type: application/json' -X GET https://api.samanage.com/incidents.json

导致 401 错误的 Python:

import json
import requests

response  = requests.get('https://api.samanage.com/incidents.json', headers={'X-Samanage-Authorization': 'API_TOKEN'})

print(response.status_code)

【问题讨论】:

  • 你可以试试headers={'X-Samanage-Authorization': 'Bearer API_TOKEN'}
  • 除了上面的注释:您使用的curl 命令与您在python代码中所做的不一样。 curl -H "X-Samanage-Authorization: Bearer API_TOKEN" -X GET https://api.samanage.com/incidents.json 是否返回正确的结果?

标签: python json curl python-requests


【解决方案1】:

根据您要执行的操作,您的问题可能是您不是 specifying the type of your credentials

尝试做:

import json
import requests

response  = requests.get('https://api.samanage.com/incidents.json', headers={'X-Samanage-Authorization': 'Bearer ' + API_TOKEN})

print(response.status_code)

在另一种情况下,如果您在输入代码时没有出错,那么您的 API_TOKEN 不是实际的令牌。您有一个 STRING API_TOKEN,但不是实际的令牌。

【讨论】:

  • 完美,标头中缺少 Bearer。我最终使用了 response = requests.get('api.samanage.com/incidents.json', headers={'X-Samanage-Authorization': 'Bearer API_TOKEN'}) !感谢您的帮助
猜你喜欢
  • 2018-02-05
  • 2019-05-19
  • 1970-01-01
  • 2021-09-10
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
相关资源
最近更新 更多