为什么当我想刷新访问令牌时会收到“无效的 grant_type”错误? - Netatmo API

问题描述 投票:0回答:1

我想刷新 Netatmo API 的访问令牌。我尝试了不同的事情,但每次都会遇到相同的错误。我使用 MicroPython 和 urequests 库来处理请求。

错误是:

状态代码:400

{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}

起初我尝试发出请求,因为它在普通 Python 中对我有用。

payload = {
    'grant_type': 'refresh_token',
    'refresh_token': 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
    'client_id': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    'client_secret': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
}

response = requests.post("https://api.netatmo.com/oauth2/token", 
   data=payload)

结果是:

TypeError: object with buffer protocol required

我发现urequests无法处理它,因为它不知道它必须使用哪个协议。

接下来我将其转换为字节数组。然后我没有收到类型错误,但收到错误 invalid_request

{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}

之后,我尝试设置标题,但得到了与没有标题相同的错误。

payload = {
        'grant_type': 'refresh_token',
        'refresh_token': 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
        'client_id': 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
        'client_secret': 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
    }

headers = {'Content-Type': 'application/x-www-form-urlencoded',}

payload_json = json.dumps(payload)
payload_bytes = bytearray(payload_json, 'utf-8')

response = requests.post('https://api.netatmo.com/oauth2/token', data=payload_bytes, headers=headers)

最后我什至尝试手动构建 URL,但仍然收到无效请求错误。 这是我尝试构建的 URL:

https://api.netatmo.com/oauth2/token?&grant_type=refresh_token&refresh_token=XXXXXXXXXXXXXXXXXXXXXXXXXX&client_id=XXXXXXXXXXXXXXXXXXXXXXXXXX&client_secret=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

有人可以帮助我吗?

python-requests micropython
1个回答
0
投票

假设问题是格式错误并且请求无法读取格式。经过与 ChatGPT 长时间交谈后,得到了对 URL 进行编码的解决方案。 ChatGPT给我的方法是:

def urlencode(params):
    encoded_str = ''
    for key, value in params.items():
        encoded_str += '{}={}&'.format(key, value)
    return encoded_str[:-1]

它非常适合我。这是它对我来说如何工作的完整代码:

import urequests as requests

def urlencode(params):
    encoded_str = ''
    for key, value in params.items():
        encoded_str += '{}={}&'.format(key, value)
    return encoded_str[:-1]

payload = {
        'grant_type': 'refresh_token',
        'refresh_token': 'XXXXXXXXXXXXXXXXXXXXXXXX',
        'client_id': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        'client_secret': 'XXXXXXXXXXXXXXXXXXXXXXXXXX',
    }

payload_encoded = urlencode(payload)
headers = {'Content-Type': 'application/x-www-form-urlencoded'}

response = requests.post('https://api.netatmo.com/oauth2/token', data=payload_encoded, headers=headers)

print(response.status_code)
print(response.text)
© www.soinside.com 2019 - 2024. All rights reserved.