首页 > 解决方案 > python请求和urllib https错误

问题描述

我想从 nasa earth api读取数据,在浏览器中打开 url 会显示数据。当我尝试使用 python 和 urllib 发出 GET 请求时,它会引发错误。

request.urlopen("https://api.nasa.gov/planetary/earth/imagery?lon=100.75&lat=1.5&date=2014-02-01&api_key=DEMO_KEY").read()

urllib.error.HTTPError:HTTP 错误 400:错误请求

当我尝试使用请求时。它返回一个错误。

r = requests.get("https://api.nasa.gov/planetary/earth/imagery?lon=100.75&lat=1.5&date=2014-02-01&api_key=DEMO_KEY")

r.content 是:

{"error": {"code": "HTTPS_REQUIRED", "message": "请求必须通过 HTTPS。尝试访问 API:https ://api.nasa.gov/planetary/earth/imagery/?lon =100.75&lat=1.5&date=2014-02-01&api_key=DEMO_KEY "}}

如果我打印出 r.url 它是 http 而不是 https:

http://api.nasa.gov/planetary/earth/imagery/?lon=100.75&lat=1.5&date=2014-02-01&api_key=DEMO_KEY

我不知道为什么会发生这种情况,我使用的是 python 3.7。任何帮助表示赞赏

标签: pythonpython-3.xpython-requests

解决方案


我能够重现你的错误。但是,当我从美国国家航空航天局网站复制链接时,它起作用了:

r = requests.get("https://api.nasa.gov/planetary/earth/imagery/?lon=100.75&lat=1.5&date=2014-02-01&api_key=DEMO_KEY")
r.json()

推荐阅读