使用Reqwest调用Spotify API获取Token时遭遇unsupported_grant_type错误的原因及解决求助
解决Spotify API获取Token时的
unsupported_grant_type错误 嘿,我一眼就揪出问题所在了——你手动设置了CONTENT_LENGTH为0,这直接让Spotify服务器忽略了你的请求体内容!
问题根源
当你发送application/x-www-form-urlencoded格式的请求时,Reqwest会自动计算并设置正确的Content-Length头。但你手动把这个头硬设为0,服务器收到后就会判定请求体是空的,自然找不到grant_type参数,所以才返回grant_type parameter is missing的错误。
修复方案
只需要删掉手动设置CONTENT_LENGTH的那一行代码就行,Reqwest会帮你自动处理这个头。修改后的get_token函数如下:
async fn get_token() -> Result<String, Box<dyn std::error::Error>> { let mut encoded = CLIENT_ID.to_string(); encoded.push_str(":"); encoded.push_str(&CLIENT_SECRET); encoded = base64::encode(encoded); let header_construct = format!("Basic {}", encoded); println!("{}", header_construct); let mut headers = header::HeaderMap::new(); headers.insert(AUTHORIZATION, header_construct.parse().unwrap()); // 移除手动设置Content-Length的代码 headers.insert( CONTENT_TYPE, HeaderValue::from_static("application/x-www-form-urlencoded"), ); let grant_string = "grant_type=client_credentials".to_string(); println!("{}", grant_string); let client = Client::new(); let body = client .post("https://accounts.spotify.com/api/token") .body(grant_string) .headers(headers) .send() .await? .text() .await?; Ok(body) }
更简洁的写法(推荐)
你还可以用Reqwest内置的form方法来构造请求体,它会自动处理URL编码和Content-Length头,避免手动构造字符串的麻烦:
async fn get_token() -> Result<String, Box<dyn std::error::Error>> { let encoded = base64::encode(format!("{}:{}", CLIENT_ID, CLIENT_SECRET)); let header_construct = format!("Basic {}", encoded); println!("{}", header_construct); let mut headers = header::HeaderMap::new(); headers.insert(AUTHORIZATION, header_construct.parse().unwrap()); let mut params = HashMap::new(); params.insert("grant_type", "client_credentials"); let client = Client::new(); let body = client .post("https://accounts.spotify.com/api/token") .form(¶ms) // 自动处理请求体编码和Content-Length .headers(headers) .send() .await? .text() .await?; Ok(body) }
额外注意点
- 确保你的
CLIENT_ID和CLIENT_SECRET是正确的,没有拼写错误或多余空格 - Authorization头的格式必须是
Basic [base64编码的client_id:client_secret],不要漏掉Basic前缀
内容的提问来源于stack exchange,提问作者MemiuCrunchy
相关产品推荐
相关产品推荐

