I'm working on an Android app that implements the Spotify API to allow the users to listen to music. I've configured the Player that Spotify has created for android devices, but it's incredibly limited in terms of its functionality, so I've had to go through Spotify's Web API to do more advanced features.
I've hit a bug when trying to get a list of the user's own playlists. I'm making a request using:
URL url = new URL("https://api.spotify.com/v1/me/playlists");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
But instead of this command going through like it does for the other web API requests I've made, it throws the error:
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$6.run(MainActivity.java:382)
at java.lang.Thread.run(Thread.java:818)
I'm not entirely sure why I'm getting this error, but I think it may have to do with not having the necessary authorization to make this request. Can anyone please help me solve this problem?
答案 0 :(得分:1)
在对文档进行了更多研究之后,我能够找到解决问题的方法。事实上我得到了错误,因为我没有使用适当的授权。
您可以使用以下代码在OnActivityResult中获取授权令牌:
AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, intent);
if (response.getType() == AuthenticationResponse.Type.TOKEN) {
authToken = response.getAccessToken();
Log.e("MainActivity","Auth Token: "+authToken.toString());
...
然后在发出URL请求时,只需将授权令牌作为标题传递。
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()));
...
另请注意,在最初形成授权请求时,您必须将启用的权限作为范围启用。