1

I am trying to get some authorisation codes from Spotify. I use the athorisation flow described here: https://developer.spotify.com/web-api/authorization-guide/#authorization-code-flow. Now I am stuck at number four: "Your application requests refresh and access tokens" I have to ask Spotify for accses_token and refresh_token with an cURL request. The cURL request has to be something like this:

curl -H "Authorization: Basic ZjM...zE=" -d grant_type=authorization_code -d code=MQCbtKe...44KN -d redirect_uri=http://localhost/codeAuslesen.php https://accounts.spotify.com/api/token

I tryed to achieve this with :

String clientId = <client_Id>;
String clientSecret = <clientSecret>;
String getTokenUrl = "https://accounts.spotify.com/api/token";

String encodeString = clientId + ":" + clientSecret;
String basicAuth = "Basic " + Base64.getEncoder().encode(encodeString.getBytes());

String url = getTokenUrl;
URL obj = new URL(url);

HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("grant_type", "authorization_code");
conn.setRequestProperty("code", code);
conn.setRequestProperty("redirect_uri", redirectUri);

try {

    BufferedReader tokenReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));  //Exception points here
    while((tokenLine = tokenReader.readLine()) != null) {
            tokenResult += tokenLine;
            }

    tokenReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(tokenResult);
}

I am just getting this Exception:

java.io.IOException: Server returned HTTP response code: 400 for URL: https://accounts.spotify.com/api/token

Does someone see what I am doing wrong?

K41
  • 11
  • 3
  • 1
    You're mixing headers and request data. See http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests for details on forming post requests in java. – TZHX Mar 23 '17 at 20:29
  • More specifically, `setRequestProperty` is setting http request headers in Java, while `-d` is setting url-encoded-form-data in cURL. – Andrew Rueckert Mar 23 '17 at 20:57
  • @TZHX: I tryed to set the -d request data like this: `String query = "grant_type=authorization_code&code="+codeOutput+"&redirect_uri="+redirectUri;`. And add them with the OutputStream: `(OutputStream output = conn.getOutputStream()) { output.write(query.getBytes()); }`. But I am still getting the same exception at the line where `conn.getInputStream()` is. – K41 Mar 23 '17 at 23:22
  • Ok, I solved it. I added a space in the String `basicAuth` after "Basic". Thank you for you help! – K41 Mar 23 '17 at 23:32

0 Answers0