Spotify Auth + HttpPost + Gson + Client Credential Flow

时间:2017-03-02 19:06:02

标签: spotify

我正在开发一个小应用程序来了解request / response / gson / etc。

我要做的是:通过Client Credential Flow获取令牌,以获得一些音频功能。

我按照指南: https://developer.spotify.com/web-api/authorization-guide/#client-credentials-flow

与spotify api的想法相同: https://github.com/thelinmichael/spotify-web-api-java/blob/master/src/main/java/com/wrapper/spotify/SpotifyHttpManager.java

尝试了差异的东西,但我现在被困住了。

目前,错误是:

HttpResponseProxy{HTTP/1.1 415 Unsupported Media Type [Server: nginx, Date: Thu, 02 Mar 2017 19:59:45 GMT, Content-Length: 888, Connection: keep-alive, Keep-Alive: timeout=600] ResponseEntityProxy{[Content-Length: 888,Chunked: false]}}

这是实际的代码:

    BASE64Encoder base64Encoder = new BASE64Encoder();

    String encodedClientIdKey = base64Encoder.encode((clientId + ":" + clientSecretKey).getBytes());
    HttpPost httpPostRequest = new HttpPost("https://accounts.spotify.com/api/token");
    httpPostRequest.setHeader("Content-Type", "application/json");
    httpPostRequest.addHeader("Authorization", "Basic " + encodedClientIdKey);

    JsonObject json = new JsonObject();
    json.addProperty("grant_type", "client_credentials");

    StringEntity stringEntity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);
    httpPostRequest.setEntity(stringEntity);

    HttpResponse post = httpClient.execute(httpPostRequest);

我认为这是一个内容类型问题,但无法通过在标题或实体上设置它来解决。

有什么想法吗?

PS:

尝试使用表单urlencoded而不是json作为内容类型,这里是代码(尝试在标题上添加内容然后作为参数):

BASE64Encoder base64Encoder = new BASE64Encoder();

    String encodedClientIdKey = base64Encoder.encode((clientId + ":" + clientSecretKey).getBytes());
    HttpPost httpPostRequest = new HttpPost("https://accounts.spotify.com/api/token");
    httpPostRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    httpPostRequest.addHeader("Authorization", "Basic " + encodedClientIdKey);

    List<NameValuePair> nameValuePairs = new ArrayList<>();
    nameValuePairs.add(new BasicNameValuePair("grant_type", "client_credentials"));
    nameValuePairs.add(new BasicNameValuePair("Content-Type", "application/x-www-form-urlencoded"));

    httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse post = httpClient.execute(httpPostRequest);
    System.out.println(post);

这次错误是Bad请求:

   HttpResponseProxy{HTTP/1.1 400 Bad Request [Server: nginx, Date: Thu, 02 Mar 2017 20:14:50 GMT, Content-Type: application/json, Content-Length: 70, Connection: keep-alive, Keep-Alive: timeout=600] ResponseEntityProxy{[Content-Type: application/json,Content-Length: 70,Chunked: false]}}

0 个答案:

没有答案
相关问题