Spotify Android - 发出授权的 Web 请求

Spotify Android - Make Authorized Web Requests

我正在开发一个 Android 应用程序,该应用程序实现了 Spotify API 以允许用户收听音乐。我已经配置了 Spotify 为 android 设备创建的播放器,但它的功能非常有限,所以我不得不通过 Spotify 的 Web API 来实现更多高级功能。

我在尝试获取用户自己的播放列表列表时遇到了一个错误。我正在使用以下方式发出请求:

URL url = new URL("https://api.spotify.com/v1/me/playlists");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

但是这个命令并没有像我发出的其他 Web API 请求那样执行,而是抛出了错误:

 java.io.FileNotFoundException: https://api.spotify.com/v1/me/playlists
                                                                               at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:242)
                                                                               at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
                                                                               at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
                                                                               at com.tmacstudios.spotifyvoice.WebWrapper$override.searchUserPlaylist(WebWrapper.java:257)
                                                                               at com.tmacstudios.spotifyvoice.WebWrapper$override.access$dispatch(WebWrapper.java)
                                                                               at com.tmacstudios.spotifyvoice.WebWrapper.searchUserPlaylist(WebWrapper.java:0)
                                                                               at com.tmacstudios.spotifyvoice.MainActivity.run(MainActivity.java:382)
                                                                               at java.lang.Thread.run(Thread.java:818)

我不完全确定为什么会收到此错误,但我认为这可能与没有必要的授权来发出此请求有关。谁能帮我解决这个问题?

在进一步研究文档之后,我找到了解决问题的方法。我实际上收到了错误,因为我没有使用正确的授权。

您可以使用此代码在 OnActivityResult 中获取授权令牌:

AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, intent);
            if (response.getType() == AuthenticationResponse.Type.TOKEN) {

                authToken = response.getAccessToken();
                Log.e("MainActivity","Auth Token: "+authToken.toString());
 ...

然后在发出 URL 请求时,只需将授权令牌作为 header 传入即可。

URL url = new URL("https://api.spotify.com/v1/me/playlists");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Bearer " + authToken);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
 ...

另请注意,在最初形成授权请求时,您必须将正在使用的权限作为范围启用。