【问题标题】:How to apply bearer token with a get?如何通过 get 应用不记名令牌?
【发布时间】:2020-01-05 17:57:18
【问题描述】:

我正在尝试访问需要不记名令牌的 API。我能够获得不记名令牌,但我不明白接下来的步骤。标头中需要令牌,但 get 只接受 2 个参数,即我的 url 和参数?

我一直在尝试模仿公司的 javascript 示例。 https://imgur.com/A7RhWo9 https://portal.trafnet.com/rest/home/JavascriptExample https://portal.trafnet.com/rest

#Urls
tokenurl = 'https://portal.trafnet.com/rest/token'

#Creds
user='test@test.com'
password='test'

#Fetch Bearer Token
tokenfetch = requests.post(tokenurl, data = {'grant_type':'password', 'username':user, 'password':password})
tokenval = tokenfetch.json()

mytoken = tokenval['access_token']

下面这行我显然不明白。

#DataParms
datefrom = '2019-09-01'
dateto = '2019-09-01'
sitecode = '01'
includeinternaloc = 'true'
datasummedbyday = 'false'



header = {'Authorization: Bearer %s' %mytoken}
params = {'SiteCode':sitecode, 'DateFrom':datefrom, 'DateTo':dateto,'IncludeInternalLocations':includeinternaloc, 'DataSummedByDay':datasummedbyday}
response = requests.post(dataurl,params,header)
print(response)
print(response.json())

{'Message': "没有找到与请求 URI 'https://portal.trafnet.com/rest/api/traffic'匹配的 HTTP 资源。"}

【问题讨论】:

    标签: python-3.x python-requests


    【解决方案1】:

    如果我正确理解了问题,那么您从发布请求中获得了不记名令牌,并且必须在标头中的下一个 GET API 调用中使用相同的令牌。要传递标头,请使用标头作为 requests.get 方法的关键字参数

    带有不记名令牌的标头示例:{'Authorization': 'Bearer ' }

    requests.get(dataurl, params=params, headers=header)
    

    【讨论】:

      猜你喜欢
      • 2017-05-07
      • 2017-11-03
      • 2022-12-12
      • 2013-02-24
      • 2020-11-08
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      相关资源
      最近更新 更多