在PyCharm中使用requests模块调用ISS API时出现连接错误
国际空间站API连接错误的解决方法
- 验证网络与接口可用性:先在浏览器中访问
https://api.open-notify.org/iss-now.json,确认接口本身可访问且你的网络能正常连接外网。如果浏览器也无法打开,大概率是网络环境受限(比如防火墙、公司/校园网络拦截)。 - 配置网络代理:如果你的网络需要通过代理访问外网,给requests添加代理配置:
import requests proxies = { 'http': 'http://你的代理地址:端口', 'https': 'http://你的代理地址:端口', } response = requests.get("https://api.open-notify.org/iss-now.json", proxies=proxies)
- 切换至HTTPS协议:将接口地址从HTTP改为HTTPS,很多公共API对HTTPS的兼容性更好,修改后的代码:
import requests response = requests.get("https://api.open-notify.org/iss-now.json")
- 添加超时与异常捕获:给请求设置超时时间,并捕获异常以便定位具体问题:
import requests try: response = requests.get("https://api.open-notify.org/iss-now.json", timeout=10) response.raise_for_status() # 触发HTTP错误状态码的异常 print(response.json()) except requests.exceptions.RequestException as e: print(f"具体错误信息: {e}")
内容的提问来源于stack exchange,提问作者abhishek pandit
相关产品推荐
相关产品推荐

