【问题标题】:Getting 403 Forbidden error when requesting JSON output with apikey使用 apikey 请求 JSON 输出时出现 403 Forbidden 错误
【发布时间】:2020-07-03 23:24:03
【问题描述】:

我正在尝试使用 Python 从服务器请求信息。 API 密钥是正确的,但我仍然收到 403 错误。它适用于 curl,但不适用于 Python。

这是输出 JSON 的 curl 代码:

curl -H "apiKey: xxx" https://kretaglobalmobileapi.ekreta.hu/api/v1/Institute/3928

这是我输出禁止错误的代码:

from urllib.request import Request, urlopen 
import json
ker = Request('https://kretaglobalmobileapi.ekreta.hu/api/v1/Institute/3928')
ker.add_header('apiKey', 'xxxx')
content = json.loads(urlopen(ker))
print(content)

有什么问题?

【问题讨论】:

    标签: python json http request urllib


    【解决方案1】:

    urlopen 通常返回一个 HTTPResponse 对象。因此,为了读取内容,请使用 read() 函数。否则,您的代码看起来不错。

    req = Request('https://kretaglobalmobileapi.ekreta.hu/api/v1/Institute/3928')
    req.add_header('apikey', 'xxx')
    content = urlopen(req).read()
    
    print(content).
    

    如果上述方法有效,您还可以使用另一个库来处理实例请求,

    r = requests.get('<MY_URI>', headers={'apikey': 'xxx'})
    

    【讨论】:

    • HTTP Error 403: Forbidden File "/home/lori/PycharmProjects/HOT/bot.py", line 5, in &lt;module&gt; content = urlopen(ker).read() 仍然无法正常工作。我认为 JSON 输出没有问题。
    • 你能尝试使用不同的库吗,我经常使用 requests 库,它大部分时间都能完成工作。 r = requests.get('&lt;MY_URI&gt;', headers={'apikey': 'xxx'})
    • 处理请求。我不知道为什么它不适用于 urllib。谢谢您的帮助!编辑你的答案,这样我就可以打勾了。
    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多