Search code examples
javaapihttp-redirectspotify

Working with Spotify API - How to follow multiple redirect links in Java?


I'm doing a Hyperskill project which uses Spotify Web Api. I'm using a Spotify Api Wrapper library (https://github.com/thelinmichael/spotify-web-api-java). I'm working with Authorization Code Flow (https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow). This means that when the user grants access, Spotify redirects me to localhost with the access token. Long story short, I am able to create a localhost server with ServerSocket and I can make the user to grant or deny access to Spotify and it's perfectly generates me the access token in the localhost link. My problem is that I can't get this access token/code from the callback link (https://example.com/callback?code=NApCCg..BkWtQ&state=profile%2Factivity). I know that I have to follow redirecting, and my guess is that Spotify makes more than 1 redirecting because my code outputs this:

https://accounts.spotify.com/login?continue=https%3A%2F%2Faccounts.spotify.com%2Fauthorize%3Fclient_id%123EXAMPLECODE%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A8080%26response_type%3Dcode

 URL url = new URL("https://accounts.spotify.com/authorize?client_id=123EXAMPLECODE&redirect_uri=http://localhost:8080&response_type=code");
 HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
 ucon.setInstanceFollowRedirects(false);
 URL secondURL = new URL(ucon.getHeaderField("Location"));
 URLConnection conn = secondURL.openConnection();
 System.out.println(secondURL);

You can see that it redirects me from "authorize" to "login" and THEN back to localhost and I am able to follow the redirecting to login. How can I make it following to localhost? Or is there any way to get this code from the callback?

I'd appreciate any help!


Solution

  • I managed to get the token from the callback link with getQuery() method of HttpExchange. Please consider this question as solved.