我应该如何在Python中处理这个HTTPS请求?

2024-05-15 00:53:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Python中使用Strava API v3,恐怕我遗漏了一些东西。医生说:

This base URL is used for all Strava API requests: https://api.strava.com

$ curl -i https://api.strava.com
HTTP/1.1 200 OK Content-Type: application/json Status: 200 OK
X-RateLimit-Limit: 5000 X-RateLimit-Remaining: 4999 Content-Length: 2

Responses are in JSON format and gzipped.

我目前正在执行以下操作:

import urllib
print urllib.urlopen('https://api.strava.com').read()

得到这个:

^{pr2}$

我不知道从哪里开始,因为我对HTTP请求和HTTPS知之甚少

更新:根据Merlin建议使用requests模块,我正在这样做:

import requests

r = requests.get('https://api.strava.com/')
print r.status_code
print r.headers['content-type']
print r.encoding
print r.text
print r.json() 

但是不断地得到一个错误:

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.strava.com', port=443): Max retries exceeded with url: / (Caused by <class 'so cket.gaierror'>: [Errno 11004] getaddrinfo failed)

Tags: httpsimportcomapijsonhttpokcontent
3条回答

您需要先按照这里的说明操作:http://strava.github.io/api/v3/oauth/ 基本上,你创建的应用程序必须授权使用它的用户(在本例中是你)。我在下面写了一些示例代码。我是python新手,所以不知道如何自动登录,所以您必须将url复制并粘贴到浏览器,然后复制并粘贴代码。在

import requests
import json

#Replace #### with your client id (listed here: http://www.strava.com/settings/api)
#Replace &&&& with your redirect uri listed on the same page. I used localhost
#Go this url in your browser and log in. Click authorize
https://www.strava.com/oauth/authorize?client_id=###&response_type=code&redirect_uri=&&&&

#Copy and paste the code returned in the url
code='qwertyuio123456789'
#Replace @@@@ with the code on your api page
values={'client_id':'###', 'client_secret':  '@@@@', 'code':code}
r = requests.post('https://www.strava.com/oauth/token', data=values)
json_string = r.text.replace("'", "\"")
values = json.loads(json_string)

#now you have an access token
r = requests.get('http://www.strava.com/api/v3/athletes/227615', params=values)

玩得开心!在

您需要使用httplib。访问HTTPS服务器的示例代码:

import httplib

con = httplib.HTTPSConnection('www.google.com')
con.request("GET", "/")
res = con.getresponse()
print res.read()

尝试使用请求!这样比较安全。 http://docs.python-requests.org/en/latest/

相关问题 更多 >

    热门问题