When I run the code in Android Studio, this method always return -1 and does not print “Search Response Data” although it can be run correctly in Intellij. I’m using Genius API from “https://rapidapi.com/Glavier/api/genius-song-lyrics1” to search for song ID and then use the song ID to search for the lyrics. Please help me to fix this!
private static int searchSong(String title) throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://genius-song-lyrics1.p.rapidapi.com/search/").newBuilder();
urlBuilder.addQueryParameter("q", title);
urlBuilder.addQueryParameter("per_page", "10");
urlBuilder.addQueryParameter("page", "1");
Request request = new Request.Builder()
.url(urlBuilder.build())
.get()
.addHeader("X-RapidAPI-Key", API_KEY)
.addHeader("X-RapidAPI-Host", HOST)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseData = response.body().string();
Log.e("Search Response Data", responseData); // Print the response data for debugging
JSONObject jsonObject = new JSONObject(responseData);
if (jsonObject.has("hits")) {
JSONArray hits = jsonObject.getJSONArray("hits");
if (hits.length() > 0) {
JSONObject firstHit = hits.getJSONObject(0);
return firstHit.getJSONObject("result").getInt("id");
}
}
else {
System.out.println("No 'response' key found in JSON");
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public String lyrics(String songTitle) throws Exception {
int songId = searchSong(songTitle);
System.out.println("fiajofjeapfjieis" + songId);
if (songId != -1) {
String htmlLyrics = getLyrics(songId);
String lyrics = htmlLyrics.replaceAll("<[^>]+>", "");
return lyrics;
} else {
return ("Guess the lyrics yourself!!");
}
}
New contributor
Moon Taeil is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.