使用Spotify Client Credentials Flow获取AuthToken时遇unsupported_grant_type错误
解决Spotify API Client Credentials Flow授权错误
问题原因
你遇到的unsupported_grant_type错误,核心原因是请求体格式与Content-Type不匹配:
- 你设置了
Content-Type: application/x-www-form-urlencoded,但实际发送的是JSON格式的请求体(通过gson.toJson()生成) - Spotify的token接口要求该类型下的请求体是
key=value形式的表单数据,无法解析JSON格式的内容,因此识别不到grant_type参数
修复方案
将请求体替换为表单格式的字符串,直接传递grant_type=client_credentials,无需JSON序列化。
修改后的Java代码:
HttpRequest authRequest = HttpRequest.newBuilder() .uri(new URI("https://accounts.spotify.com/api/token")) .header("Authorization", "Basic " + Utilities.EncodeBase64(id + ":" + key)) .header("Content-Type", "application/x-www-form-urlencoded") .POST(BodyPublishers.ofString("grant_type=client_credentials")) .build();
验证要点
- 确保
Authorization头的Base64编码正确(客户端ID和密钥用冒号分隔后编码) - 请求体严格使用
grant_type=client_credentials的纯文本格式,不要添加任何JSON结构
内容的提问来源于stack exchange,提问作者Marlon Müller
相关产品推荐
相关产品推荐

