I had this code working for the same site but they changed the theme and now i\'m struggling. What could i be doing wrong here to get the url of the youtube video?
Alternatively, here is a Jsoup only solution:
/**
*
* /!\ Exceptions raised by this method are NOT logged. /!\
*
* @param youtubeUrl
* @return videoId or null if an exception occured
*
*/
public static String extractVideoId(String youtubeUrl) {
String videoId = null;
try {
Document videoPage = Jsoup.connect(youtubeUrl).get();
Element videoIdMeta = videoPage.select("div[itemtype=http://schema.org/VideoObject] meta[itemprop=videoId]").first();
if (videoIdMeta == null) {
throw new IOException("Unable to find videoId in HTML content.");
}
videoId = videoIdMeta.attr("content");
} catch (Exception e) {
e.printStackTrace(); // alternatively you may log this exception...
}
return videoId;
}
The Best Way is
code =youtubeUrl.substring(youtubeUrl.length() - 11);
The code is correct so far but I just was wrongly extracting the video id from the video url. Using this method worked
public static String extractVideoId(String ytUrl) {
String vId = null;
Pattern pattern = Pattern.compile(".*(?:youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=)([^#\\&\\?]*).*");
Matcher matcher = pattern.matcher(ytUrl);
if (matcher.matches()){
vId = matcher.group(1);
}
return vId;
}