Anonymous
Код ответа HTTP: 401 с использованием API Spotify.
Сообщение
Anonymous » 13 дек 2024, 15:29
У меня есть этот класс:
Код: Выделить всё
@Slf4j
@Service
@Transactional(readOnly = true)
public class SpotifyService {
@Value("${spring.security.oauth2.client.registration.spotify.client-id}")
private String CLIENT_ID;
@Value("${spring.security.oauth2.client.registration.spotify.client-secret}")
private String CLIENT_SECRET;
private static final String TOKEN_URL = "https://accounts.spotify.com/api/token";
private static final String USER_ID = "31kju9weutglbdijioclkgia645jno4";
public void createList (JSONObject playlistPayload) {
try {
String accessToken = fetchAccessToken();
log.info("Access token: " + accessToken);
// Define the endpoint URL
String endpoint = "https://api.spotify.com/v1/users/" + USER_ID + "/playlists";
// Create the playlist
URL url = new URL(endpoint);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = playlistPayload.toString().getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// Obtener el playlistId desde la respuesta JSON
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_CREATED) {
log.info("Playlist created successfully!");
// Read the response to extract the playlist ID
try (InputStream responseStream = connection.getInputStream()) {
String response = new String(responseStream.readAllBytes(), StandardCharsets.UTF_8);
JSONObject jsonResponse = new JSONObject(response);
String playlistId = jsonResponse.getString("id");
// Log the link to the playlist
String playlistLink = "https://open.spotify.com/playlist/" + playlistId;
log.info("Playlist link: " + playlistLink);
// Add tracks to the playlist
addTracksToPlaylist(playlistId, playlistPayload.getJSONArray("tracks"), accessToken);
}
} else {
log.error("Failed to create playlist. HTTP response code: " + responseCode);
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
private static void addTracksToPlaylist(String playlistId, JSONArray tracks, String accesToken) {
try {
// Define the endpoint URL for adding tracks
String endpoint = "https://api.spotify.com/v1/playlists/" + playlistId + "/tracks";
// Prepare the JSON payload for adding tracks
JSONObject tracksPayload = new JSONObject();
tracksPayload.put("uris", tracks);
URL url = new URL(endpoint);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Bearer " + accesToken);
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = tracksPayload.toString().getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_CREATED) {
//System.out.println("Tracks added successfully to the playlist!");
} else {
log.error("Failed to add tracks. HTTP response code: " + responseCode);
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
private String fetchAccessToken() {
try {
URL url = new URL(TOKEN_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Basic " + encodeClientCredentials(CLIENT_ID, CLIENT_SECRET));
connection.setDoOutput(true);
String body = "grant_type=client_credentials";
try (OutputStream os = connection.getOutputStream()) {
byte[] input = body.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String response = new String(connection.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
JSONObject jsonResponse = new JSONObject(response);
return jsonResponse.getString("access_token");
} else {
log.error("Failed to fetch access token. HTTP response code: " + responseCode);
}
} catch (Exception e) {
log.error("Error fetching access token: " + e.getMessage());
}
return null;
}
private String encodeClientCredentials(String clientId, String clientSecret) {
String credentials = clientId + ":" + clientSecret;
return java.util.Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
}
}
но при запуске службы возникает ошибка: не удалось создать список воспроизведения. Код ответа HTTP: 401
Подробнее здесь:
https://stackoverflow.com/questions/792 ... potify-api
1734092942
Anonymous
У меня есть этот класс: [code]@Slf4j @Service @Transactional(readOnly = true) public class SpotifyService { @Value("${spring.security.oauth2.client.registration.spotify.client-id}") private String CLIENT_ID; @Value("${spring.security.oauth2.client.registration.spotify.client-secret}") private String CLIENT_SECRET; private static final String TOKEN_URL = "https://accounts.spotify.com/api/token"; private static final String USER_ID = "31kju9weutglbdijioclkgia645jno4"; public void createList (JSONObject playlistPayload) { try { String accessToken = fetchAccessToken(); log.info("Access token: " + accessToken); // Define the endpoint URL String endpoint = "https://api.spotify.com/v1/users/" + USER_ID + "/playlists"; // Create the playlist URL url = new URL(endpoint); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", "Bearer " + accessToken); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); try (OutputStream os = connection.getOutputStream()) { byte[] input = playlistPayload.toString().getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); } // Obtener el playlistId desde la respuesta JSON int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_CREATED) { log.info("Playlist created successfully!"); // Read the response to extract the playlist ID try (InputStream responseStream = connection.getInputStream()) { String response = new String(responseStream.readAllBytes(), StandardCharsets.UTF_8); JSONObject jsonResponse = new JSONObject(response); String playlistId = jsonResponse.getString("id"); // Log the link to the playlist String playlistLink = "https://open.spotify.com/playlist/" + playlistId; log.info("Playlist link: " + playlistLink); // Add tracks to the playlist addTracksToPlaylist(playlistId, playlistPayload.getJSONArray("tracks"), accessToken); } } else { log.error("Failed to create playlist. HTTP response code: " + responseCode); } } catch (Exception e) { log.error(e.getMessage()); } } private static void addTracksToPlaylist(String playlistId, JSONArray tracks, String accesToken) { try { // Define the endpoint URL for adding tracks String endpoint = "https://api.spotify.com/v1/playlists/" + playlistId + "/tracks"; // Prepare the JSON payload for adding tracks JSONObject tracksPayload = new JSONObject(); tracksPayload.put("uris", tracks); URL url = new URL(endpoint); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", "Bearer " + accesToken); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); try (OutputStream os = connection.getOutputStream()) { byte[] input = tracksPayload.toString().getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); } int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_CREATED) { //System.out.println("Tracks added successfully to the playlist!"); } else { log.error("Failed to add tracks. HTTP response code: " + responseCode); } } catch (Exception e) { log.error(e.getMessage()); } } private String fetchAccessToken() { try { URL url = new URL(TOKEN_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Authorization", "Basic " + encodeClientCredentials(CLIENT_ID, CLIENT_SECRET)); connection.setDoOutput(true); String body = "grant_type=client_credentials"; try (OutputStream os = connection.getOutputStream()) { byte[] input = body.getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); } int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { String response = new String(connection.getInputStream().readAllBytes(), StandardCharsets.UTF_8); JSONObject jsonResponse = new JSONObject(response); return jsonResponse.getString("access_token"); } else { log.error("Failed to fetch access token. HTTP response code: " + responseCode); } } catch (Exception e) { log.error("Error fetching access token: " + e.getMessage()); } return null; } private String encodeClientCredentials(String clientId, String clientSecret) { String credentials = clientId + ":" + clientSecret; return java.util.Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); } } [/code] но при запуске службы возникает ошибка: не удалось создать список воспроизведения. Код ответа HTTP: 401 Подробнее здесь: [url]https://stackoverflow.com/questions/79278331/http-response-code-401-using-spotify-api[/url]