Plan: Premium
Country: USA
Device: Odroid H2
Operating System: Linux 19.10
My Question or Issue
I am working on a Java client. I have been able to access the whole API with no problem with the ironic exception of authorization. I would be quite happy if you could point me to any working Java example of getting the client_credentials token. The message I am currently getting and source code I am using are below:
Bad Request
400: Bad Request
{"error":"unsupported_grant_type","error_description":"grant_type parameter is missing"}
<<< Finished >>>
public static void main(final String[] args) {
getToken();
System.out.println("<<< Finished >>>");
}
private static final String CHARSET = "UTF-8";
private static final String GRANT_TYPE = "client_credentials";
public static String getToken() {
String PAYLOAD;
try {
// PAYLOAD = String.format("client_id=%s&client_secret=%s&grant_type=%s",
// URLEncoder.encode(CLIENT_ID, CHARSET),
// URLEncoder.encode(CLIENT_SECRET, CHARSET),
// URLEncoder.encode(GRANT_TYPE, CHARSET));
PAYLOAD = "grant_type=" + URLEncoder.encode("client_credentials", "UTF-8");
} catch (final UnsupportedEncodingException x) {
PAYLOAD = "";
x.printStackTrace();
}
String response = "";
try {
final URL url = new URL("https://accounts.spotify.com/api/token");
try {
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("grant_type", "client_credentials");
connection.setRequestProperty("Authorization", "Basic " + CLIENT_ID + ':' + CLIENT_SECRET);
connection.setRequestProperty("Content-Length", "" + PAYLOAD.length());
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
try (final DataOutputStream writer = new DataOutputStream(connection.getOutputStream())) {
writer.writeChars("PAYLOAD");
}
if (connection.getResponseCode() == 200) {
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
while (reader.ready()) {
System.out.println(reader.readLine());
}
}
} else {
System.out.println(connection.getResponseMessage());
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
while (reader.ready()) {
System.out.println(connection.getResponseCode() + ": " + connection.getResponseMessage());
System.out.println(reader.readLine());
}
}
}
} catch (final IOException x) {
x.printStackTrace();
}
} catch (final MalformedURLException x) {
x.printStackTrace();
}
return response;
}