Spotify:发布到 api/token 给出了错误的请求,但在 curl 中工作

Posted

技术标签:

【中文标题】Spotify:发布到 api/token 给出了错误的请求,但在 curl 中工作【英文标题】:Spotify: post to api/token gives bad request but works in curl 【发布时间】:2018-03-18 18:21:17 【问题描述】:

我正在尝试通过 Authorization Code Flow 从 spotify web api 获取访问令牌。在 curl 中执行请求时,它按预期将令牌返回给我:

curl -H "Authorization: Basic Mj...zk=" -d grant_type=authorization_code -d code=AQ...Ew -d redirect_uri=http://localhost:8081/callback https://accounts.spotify.com/api/token

但是,当我尝试在 java 代码中执行相同的请求时,我收到 400 bad request:

    final String url = "https://accounts.spotify.com/api/token";

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("grant_type", "authorization_code"));
    params.add(new BasicNameValuePair("code", req.getParameter("code")));
    params.add(new BasicNameValuePair("redirect_uri ", "http://localhost:8081/callback"));


    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    httpPost.setHeader(HttpHeaders.AUTHORIZATION,"Basic " +  Base64.encodeBase64String(("2...0" + ":" + "4...9").getBytes()));
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

    CloseableHttpResponse response = client.execute(httpPost);
    System.out.println(response);

这是我得到的错误响应:

HttpResponseProxyHTTP/1.1 400 Bad Request [Server: nginx, Date: Fri, 06 Oct 2017 21:20:39 GMT, Content-Type: application/json, Content-Length: 68, Connection: keep-alive, Keep-Alive: timeout=600] ResponseEntityProxy[Content-Type: application/json,Content-Length: 68,Chunked: false]

我错过了什么或做错了什么?

【问题讨论】:

不能在发送之前将文本输出到字符串吗? 【参考方案1】:

通过使用 StringEntity 而不是 UrlEncodedFormEntity 自己修复了它:

    final String url = "https://accounts.spotify.com/api/token";
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.encodeBase64String(("2...0" + ":" + "4...9").getBytes()));
    StringEntity data = new StringEntity("grant_type=authorization_code&&code=" + req.getParameter("code") + "&&redirect_uri=http://localhost:8081/callback");
    httpPost.setEntity(data);

    HttpResponse response = client.execute(httpPost);

【讨论】:

老兄!这与人们预期的相差很大。非常感谢您!

以上是关于Spotify:发布到 api/token 给出了错误的请求,但在 curl 中工作的主要内容,如果未能解决你的问题,请参考以下文章

使用 fetch 时 POST https://accounts.spotify.com/api/token 415 错误

requests.exceptions.HTTPError:400 客户端错误:对 url 的错误请求:https://accounts.spotify.com/api/token

在 Google 脚本中: UrlFetchApp.fetch(''https://accounts.spotify.com/api/token'') 返回代码 405

无法从 Spotify API 获取访问令牌

从响应 url 中提取令牌 - Spotify API

Spotify Web Api 令牌请求响应 400