【问题标题】:Why does request.get(url).json get a bad request but .text does not?为什么 request.get(url).json 收到错误的请求而 .text 没有?
【发布时间】:2022-01-18 14:37:11
【问题描述】:

使用此链接 https://www.googleapis.com/oauth2/v1/tokeninfo?access_token= 编写一些 python 来验证 OAuth2 令牌

import requests

def verify(token):
    url = "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={auth_token}".format(auth_token = token)
    response = requests.get(url).text
    print(response)
    

if __name__ == "__main__":
    verify(2)

由于 .text 属性,这将返回下面的 json(这是正确的)但在字符串中。但是,如果我使用 .json 代替,我会得到 400 状态码。自从我使用 python 以来已经有一段时间了,如果我错过了一些明显的东西,请道歉。

{
  "error": "invalid_token",
  "error_description": "Invalid Value"
}

与此同时,我使用 json 库来加载字符串,但似乎没有必要。

【问题讨论】:

    标签: python api python-requests bad-request


    【解决方案1】:
    import requests
    
    
    def verify(token):
        url = f"https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={token}"
        response = requests.get(url).json()
        print(response)
    
    
    if __name__ == "__main__":
        verify(2)
    

    您正在使用 .json 而不是 .json() 导致问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 2021-09-15
      • 2016-03-30
      • 1970-01-01
      相关资源
      最近更新 更多