PYTHON: requests.post() 如何将 request_body 编码为 application/x-www-form-urlencoded
PYTHON: requests.post() how to send request_body encoded as application/x-www-form-urlencoded
我正在使用 Spotify API 开发一个应用程序。我的问题是我正在尝试获取 access_token
但它不起作用。在文档中,它说我需要发送编码为 application/x-www-form-urlencoded 的正文,所以我搜索了一下,只需将 request_body
设置为字典就可以了。
这是我的函数代码:
def get_access_token(self):
auth_code, code_verifier = self.get_auth_code()
endpoint = "https://accounts.spotify.com/api/token"
# as docs said data should be encoded as application/x-www-form-urlencoded
# as internet says i just need to send it as a dictionary. However it's not working
request_body = {
"client_id": f"{self.client_ID}",
"grant_type": "authorization_code",
"code": f"{auth_code}",
"redirect_uri": f"{self.redirect_uri}",
"code_verifier": f"{code_verifier}"
}
response = requests.post(endpoint, data=request_body)
print(response)
我得到的回复总是 <Response [400]>
这是文档,第 4 步 https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow-with-proof-key-for-code-exchange-pkce
注意:我尝试将其作为 curl 执行并且工作正常我不确定我在 python 代码中做错了什么
这是命令:
curl -d client_id={self.client_ID} -d grant_type=authorization_code -d code={auth_code} -d redirect_uri={self.redirect_uri} -d code_verifier={code_verifier} https://accounts.spotify.com/api/token
您可以在请求头中指定请求类型。
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post(endpoint, data=request_body, headers=headers)
print(response)
我正在使用 Spotify API 开发一个应用程序。我的问题是我正在尝试获取 access_token
但它不起作用。在文档中,它说我需要发送编码为 application/x-www-form-urlencoded 的正文,所以我搜索了一下,只需将 request_body
设置为字典就可以了。
这是我的函数代码:
def get_access_token(self):
auth_code, code_verifier = self.get_auth_code()
endpoint = "https://accounts.spotify.com/api/token"
# as docs said data should be encoded as application/x-www-form-urlencoded
# as internet says i just need to send it as a dictionary. However it's not working
request_body = {
"client_id": f"{self.client_ID}",
"grant_type": "authorization_code",
"code": f"{auth_code}",
"redirect_uri": f"{self.redirect_uri}",
"code_verifier": f"{code_verifier}"
}
response = requests.post(endpoint, data=request_body)
print(response)
我得到的回复总是 <Response [400]>
这是文档,第 4 步 https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow-with-proof-key-for-code-exchange-pkce
注意:我尝试将其作为 curl 执行并且工作正常我不确定我在 python 代码中做错了什么
这是命令:
curl -d client_id={self.client_ID} -d grant_type=authorization_code -d code={auth_code} -d redirect_uri={self.redirect_uri} -d code_verifier={code_verifier} https://accounts.spotify.com/api/token
您可以在请求头中指定请求类型。
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post(endpoint, data=request_body, headers=headers)
print(response)