【问题标题】:Post request failing with python httplib2, works with curl使用 python httplib2 发布请求失败,适用于 curl
【发布时间】:2017-02-25 01:21:15
【问题描述】:

我正在尝试从 fitbit API 请求访问令牌,但它一直返回 401 Unauthorized 状态,即使我将请求配置为与相应的 curl 查询相同 - 这成功了。返回的错误消息说:"errorType":"invalid_client","message":"Invalid authorization header format. httplib2 构建其请求的方式是否存在一些细微差别,这让我感到厌烦?...

(工作)卷曲查询:

curl    -X POST -i 
-H 'Authorization: Basic <LONG_CODE>'
-H 'Content-Type: application/x-www-form-urlencoded' 
-d "clientId=<CLIENT_ID>" 
-d "grant_type=authorization_code" 
-d "redirect_uri=http%3A%2F%2F127.0.0.1%3A5000%2Ffitbit-callback" 
-d "code=<AUTHORIZATION_GRANT_CODE>" 
https://api.fitbit.com/oauth2/token

不工作的 python 请求(已编辑):

TOKEN_URL = 'https://api.fitbit.com'/oauth2/token'
CALLBACK_URI  = 'http://127.0.0.1:5000/fitbit-callback'

auth_header = base64.b64encode(bytes(<CLIENT_ID> + ':' + <CLIENT_SECRET>, 'utf-8'))
headers = {
    'Authorization': 'Basic %s' % auth_header,
    'Content-Type' : 'application/x-www-form-urlencoded'
    }

params = {
    'client_id': <CLIENT_ID>,
    'grant_type': 'authorization_code',
    'redirect_uri': CALLBACK_URI,
    'code': <AUTHORIZATION_GRANT_CODE>
    }
urlparams = urlencode(params)

resp, content = h.request(TOKEN_URL, 
    'POST', 
    urlparams,
    headers)

从代码中看不出来:

  • python 中的auth_header 变量匹配&lt;LONG_CODE&gt;

python3 fitbit.py后的终端回复:

send: b"POST /oauth2/token HTTP/1.1\r\nHost: api.fitbit.com\r\nContent-Length: 153\r\nauthorization: Basic b'<LONG_CODE>'\r\ncontent-type: application/x-www-form-urlencoded\r\nuser-agent: Python-httplib2/0.10.3 (gzip)\r\naccept-encoding: gzip, deflate\r\n\r\n"
send: b'client_id=<CLIENT_ID>&grant_type=authorization_code&redirect_uri=http%3A%2F%2F127.0.0.1%3A5000%2Ffitbit-callback&code=<AUTHORIZATION_GRANT_CODE>'
reply: 'HTTP/1.1 401 Unauthorized\r\n'
header: Date header: Content-Type header: Transfer-Encoding header: Connection header: Cache-control header: WWW-Authenticate header: Content-Language header: Content-Encoding header: Vary header: X-Frame-Options header: Server header: CF-RAY 

运行print(content):

b'{"errors":[{"errorType":"invalid_client","message":"Invalid authorization header format. Visit https://dev.fitbit.com/docs/oauth2 for more information on the Fitbit Web API authorization process."}],"success":false}'

【问题讨论】:

    标签: python post oauth httplib2 fitbit


    【解决方案1】:

    这很尴尬。在将请求定向到让我分析它们的请求捕获服务(如 runscope)之前,我没有注意到它,但我似乎只是错过了 python 示例中的b'&lt;LONG_CODE&gt;' 格式。这修复了它:

    auth_header.decode("utf-8")

    也许这个问题应该被删除,如果它不太可能帮助其他人......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 2021-09-21
      • 2020-03-12
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 2019-12-19
      相关资源
      最近更新 更多