0

I'm building a little application and i need to use the spoify API, when I try to login I have

400 ERROR:{"error":"unsupported_grant_type","error_description":"grant_type parameter is missing"}

when I make the POST request

        String urlString = "https://accounts.spotify.com/api/token?";

        URL website = new URL(urlString);

        HttpURLConnection connection = (HttpURLConnection) website.openConnection();
        connection.setRequestMethod("POST");


        // Headers
        String toEncode = Test.CLIENT_ID + ":" + Test.CLIEN_SECRET_ID;
        String encodedString = Base64.getEncoder().encodeToString(toEncode.getBytes());

        connection.setRequestProperty("Authorization", encodedString);//client id + secret
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setDoOutput(true);

        // Add parameters to the body
        String jsonInputString = "{" +
                "grant_type: authorization_code,\n" +
                "\"redirect_uri\": \"" + Test.REDIRECT_URI + "\",\n" +
                "\"code\": \"" + code +
                "\"\n}";

        System.out.println("json input string   " +jsonInputString);

        byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
        connection.setFixedLengthStreamingMode(input.length);
        connection.connect();

        try (OutputStream os = connection.getOutputStream()) {
            os.write(input);
        }

I read a lot about this error but I cannot find who to correct it, I also asked other people to look at my code and check if I did something wrong they don't find it either.

Please tell me you see what's wrong and how I can correct it

elhi
  • 21
  • 2

1 Answers1

0

As far as I see you are trying to do the authorization with OAuth2. I recommend, you to read https://datatracker.ietf.org/doc/html/rfc6749, which explains what you are doing. Besides, if possible use some libraries, which are doing the OAuth2 flows for you.

Furthermore from what I see in your code, you should try to pass the values in your JSON as form parameters. See also https://stackoverflow.com/a/13486223/17832003

List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("grant_type", "authorization_code"));
formParams.add(new BasicNameValuePair("redirect_uri", Test.REDIRECT_URI));
formParams.add(new BasicNameValuePair("code", code));

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
    new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

conn.connect();
Tavark
  • 29
  • 2
  • omg thank you so much, I saw that "NameValuePair" was deprecated on the second link and someone explained how to make it now I finally correct that problem. Love u bro <3 – elhi Feb 26 '22 at 14:12