You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Java调用Spotify API获取AuthToken时遇grant_type错误

解决Spotify API获取Access Token时的unsupported_grant_type错误

问题本质

你遇到的错误核心是请求体格式与API要求不匹配:

  • 你设置了Content-Type: application/x-www-form-urlencoded请求头,但实际发送的是JSON格式的请求体(通过Gson序列化Transcript类生成)。
  • Spotify的Client Credentials授权流程要求请求体必须是表单键值对格式(key=value),服务器无法从JSON内容中解析出grant_type参数,因此返回"grant_type parameter is missing"错误。

修正方案

直接构造符合API要求的表单格式请求体,替换原有的JSON序列化逻辑:

修正后的完整代码

public static void getAuthToken() throws Exception {
    // 构造表单格式的请求体,这是Spotify API要求的格式
    String formRequestBody = "grant_type=client_credentials";
    String originalInput = Access.CLIENT_ID + ":" + Access.CLIENT_SECRET;
    String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());

    HttpRequest postRequest = HttpRequest.newBuilder()
            .uri(new URI("https://accounts.spotify.com/api/token"))
            .POST(HttpRequest.BodyPublishers.ofString(formRequestBody))
            .header("Authorization", "Basic " + encodedString)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .build();

    HttpClient httpClient = HttpClient.newHttpClient();
    HttpResponse<String> postResponse = httpClient.send(postRequest, HttpResponse.BodyHandlers.ofString());
    System.out.println(postResponse.body());
}

关键修改点

  • 移除了Gson序列化Transcript类的逻辑,直接使用字符串"grant_type=client_credentials"作为请求体,完全匹配Spotify API的格式要求。
  • 保留Content-Type头为application/x-www-form-urlencoded,确保服务器能正确解析请求体内容。

扩展说明

如果后续需要添加更多表单参数(比如其他授权类型的附加参数),只需用&拼接键值对即可,示例格式:

"grant_type=authorization_code&code=授权码内容&redirect_uri=回调地址"

内容的提问来源于stack exchange,提问作者kalle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 16:45:30