Getting Started with YouTube Java API
In this tutorial I am taking a look at Google’s YouTube API which allows you to empower your application with YouTube’s features. YouTube is one of the “killer” Internet applications and its traffic comprises of a huge portion of the total internet traffic.
Before we get started, make sure you have read the API Overview Guide. We will mainly deal with the Data API, which allows you to perform many of the operations available on the YouTube website (search for videos, retrieve standard feeds, see related content etc.).
The API is available in multiple programming languages and we will be using Java for this tutorial. Read the Java Developer’s Guide to get a first idea. Also bookmark the Google Data API JavaDoc page.
Let’s prepare the development environment. First, download the GData Java Client from the corresponding download section. I will be using the 1.41.2 version for this tutorial. Note that there is also a version 2, but according to the site is experimental and not compatible with version 1.
Extract the zipped file, locate the folder “gdata\java\lib” and include the following JARs into your application’s classpath:
- data-client-1.0.jar
- gdata-youtube-2.0.jar
- gdata-core-1.0.jar
- gdata-media-1.0.jar
Next, we have to take care of the dependencies. The list of dependency packages can be found here.
- The JavaMail API is included for media support. It can be downloaded here. The “mail.jar” is needed.
- The Google Collections Library is also internally used by the GData client. I downloaded the 1.0-final version. The “google-collect-1.0.jar” is needed.
Make sure all the aforementioned JAR files are included in the project’s classpath.
Note that all public feeds are read-only and do not require any authentication. Authenticated operations, on the other hand, are those that include the retrieval of private feeds, such as a user’s inbox feed, as well as write, upload, update and delete operations. You will need to sign up for a developer key to be able to execute authenticated operations. No key is required for this tutorial though.
Now that the infrastructure is ready, let’s talk a bit about the API. The main class that we will be using is the YouTubeService class. This allows you to perform search queries similar to the ones that you can perform while browsing YouTube’s web page. Each query is represented by a YouTubeQuery instance. The results of each query (if any), come in the form of a VideoFeed object.
From each feed, a number of VideoEntry objects can be retrieved. From a VideoEntry, we extract a YoutTubeMediaGroup object. You can imagine this class as a placeholder for media information (check the “Media RSS” Specification). We then retrieve the corresponding MediaPlayer and finally the player URL. We can also get information about the accompanying thumbnails, via the MediaThumbnail class.
Let’s get started with the code. First we create two model classes which will be used to hold information about the feeds and the videos. The first one is called YouTubeMedia and contains the media content URL and the media content type. The second one is named YouTubeVideo and contains all the information regarding a specific video (URL, embedded player URL, thumbnails and instances of YoutTubeMedia). The source code for these is following:
package com.javacodegeeks.youtube.model; public class YouTubeMedia { private String location; private String type; public YouTubeMedia(String location, String type) { super(); this.location = location; this.type = type; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
package com.javacodegeeks.youtube.model; import java.util.List; public class YouTubeVideo { private List<String> thumbnails; private List<YouTubeMedia> medias; private String webPlayerUrl; private String embeddedWebPlayerUrl; public List<String> getThumbnails() { return thumbnails; } public void setThumbnails(List<String> thumbnails) { this.thumbnails = thumbnails; } public List<YouTubeMedia> getMedias() { return medias; } public void setMedias(List<YouTubeMedia> medias) { this.medias = medias; } public String getWebPlayerUrl() { return webPlayerUrl; } public void setWebPlayerUrl(String webPlayerUrl) { this.webPlayerUrl = webPlayerUrl; } public String getEmbeddedWebPlayerUrl() { return embeddedWebPlayerUrl; } public void setEmbeddedWebPlayerUrl(String embeddedWebPlayerUrl) { this.embeddedWebPlayerUrl = embeddedWebPlayerUrl; } public String retrieveHttpLocation() { if (medias==null || medias.isEmpty()) { return null; } for (YouTubeMedia media : medias) { String location = media.getLocation(); if (location.startsWith("http")) { return location; } } return null; } }
Finally, the YouTubeManager class is presented. It can be used to perform search queries and returns instances of the YouTubeVideo model class with all the relevant information. It also creates the appropriate embedded web player URL. Here is the code for that class:
package com.javacodegeeks.youtube; import java.net.URL; import java.util.LinkedList; import java.util.List; import com.google.gdata.client.youtube.YouTubeQuery; import com.google.gdata.client.youtube.YouTubeService; import com.google.gdata.data.media.mediarss.MediaThumbnail; import com.google.gdata.data.youtube.VideoEntry; import com.google.gdata.data.youtube.VideoFeed; import com.google.gdata.data.youtube.YouTubeMediaContent; import com.google.gdata.data.youtube.YouTubeMediaGroup; import com.javacodegeeks.youtube.model.YouTubeMedia; import com.javacodegeeks.youtube.model.YouTubeVideo; public class YouTubeManager { private static final String YOUTUBE_URL = "http://gdata.youtube.com/feeds/api/videos"; private static final String YOUTUBE_EMBEDDED_URL = "http://www.youtube.com/v/"; private String clientID; public YouTubeManager(String clientID) { this.clientID = clientID; } public List<YouTubeVideo> retrieveVideos(String textQuery, int maxResults, boolean filter, int timeout) throws Exception { YouTubeService service = new YouTubeService(clientID); service.setConnectTimeout(timeout); // millis YouTubeQuery query = new YouTubeQuery(new URL(YOUTUBE_URL)); query.setOrderBy(YouTubeQuery.OrderBy.VIEW_COUNT); query.setFullTextQuery(textQuery); query.setSafeSearch(YouTubeQuery.SafeSearch.NONE); query.setMaxResults(maxResults); VideoFeed videoFeed = service.query(query, VideoFeed.class); List<VideoEntry> videos = videoFeed.getEntries(); return convertVideos(videos); } private List<YouTubeVideo> convertVideos(List<VideoEntry> videos) { List<YouTubeVideo> youtubeVideosList = new LinkedList<YouTubeVideo>(); for (VideoEntry videoEntry : videos) { YouTubeVideo ytv = new YouTubeVideo(); YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup(); String webPlayerUrl = mediaGroup.getPlayer().getUrl(); ytv.setWebPlayerUrl(webPlayerUrl); String query = "?v="; int index = webPlayerUrl.indexOf(query); String embeddedWebPlayerUrl = webPlayerUrl.substring(index+query.length()); embeddedWebPlayerUrl = YOUTUBE_EMBEDDED_URL + embeddedWebPlayerUrl; ytv.setEmbeddedWebPlayerUrl(embeddedWebPlayerUrl); List<String> thumbnails = new LinkedList<String>(); for (MediaThumbnail mediaThumbnail : mediaGroup.getThumbnails()) { thumbnails.add(mediaThumbnail.getUrl()); } ytv.setThumbnails(thumbnails); List<YouTubeMedia> medias = new LinkedList<YouTubeMedia>(); for (YouTubeMediaContent mediaContent : mediaGroup.getYouTubeContents()) { medias.add(new YouTubeMedia(mediaContent.getUrl(), mediaContent.getType())); } ytv.setMedias(medias); youtubeVideosList.add(ytv); } return youtubeVideosList; } }
In order to test our class, as well provide a show case example, we create the following simple test class:
package com.javacodegeeks.youtube.test; import java.util.List; import com.javacodegeeks.youtube.YouTubeManager; import com.javacodegeeks.youtube.model.YouTubeVideo; public class YouTubeTester { public static void main(String[] args) throws Exception { String clientID = "JavaCodeGeeks"; String textQuery = "java code"; int maxResults = 10; boolean filter = true; int timeout = 2000; YouTubeManager ym = new YouTubeManager(clientID); List<YouTubeVideo> videos = ym.retrieveVideos(textQuery, maxResults, filter, timeout); for (YouTubeVideo youtubeVideo : videos) { System.out.println(youtubeVideo.getWebPlayerUrl()); System.out.println("Thumbnails"); for (String thumbnail : youtubeVideo.getThumbnails()) { System.out.println("\t" + thumbnail); } System.out.println(youtubeVideo.getEmbeddedWebPlayerUrl()); System.out.println("************************************"); } } }
The Eclipse project for this tutorial, including the dependency libraries, can be downloaded here.
Enjoy!
- GWT 2 Spring 3 JPA 2 Hibernate 3.5 Tutorial
- Getting Started with SmartGWT for awesome GWT interfaces
- JAX–WS with Spring and Maven Tutorial
- Sending e-mails in Java with Spring – GMail SMTP server example
- Java Tutorials and Android Tutorials list
Thank you very very much!
I need help with rtsp link …please help.
Hi I am getting this exception, please help:
Exception in thread “main” java.lang.NoSuchMethodError: com.google.gdata.data.ExtensionProfile.declareAdditionalNamespace(Lcom/google/gdata/util/common/xml/XmlWriter$Namespace;)V
at com.google.gdata.data.youtube.CommentEntry.declareExtensions(CommentEntry.java:92)
at com.google.gdata.data.ExtensionProfile.addDeclarations(ExtensionProfile.java:71)
at com.google.gdata.data.BaseFeed.declareExtensions(BaseFeed.java:229)
at com.google.gdata.data.ExtensionProfile.addDeclarations(ExtensionProfile.java:71)
at com.google.gdata.client.youtube.YouTubeService.(YouTubeService.java:140)
at com.google.gdata.client.youtube.YouTubeService.(YouTubeService.java:103)
at YouTubeExample.main(YouTubeExample.java:21)
have the same problem. Any clue ?
It works on Eclipes but netbeans throws an exception NoSuchMethodError
thank u..I m done with this…I m working on project of developing youtube webcrawler..
So ,I need to know further steps..
Exception in thread “main” java.lang.NoSuchMethodError: com.google.common.collect.ImmutableSet.copyOf([Ljava/lang/Object;)Lcom/google/common/collect/ImmutableSet;
at com.google.gdata.wireformats.AltFormat$Builder.setAcceptableTypes(AltFormat.java:399)
at com.google.gdata.wireformats.AltFormat$Builder.setAcceptableXmlTypes(AltFormat.java:387)
at com.google.gdata.wireformats.AltFormat.(AltFormat.java:49)
at com.google.gdata.client.Service.(Service.java:558)
at co.exalta.youtube.model.YTManager.retrieveVideos(YTManager.java:30)
at co.exalta.youtube.tester.YouTubeTester.main(YouTubeTester.java:20)
how to convert youtube videos to text file using java can u please help me
Thanks in Advance
Hi,
Great artical, Really help a lot.
But I have one question.
If I not setting proxy and port in my code, It will not work.
So I use
System.setProperty(“proxyHost”,);
System.setProperty(“proxyPort”, );
But this will effect in my other code.
So is ther any alternative to set proxy and port.
Please also refer http://stackoverflow.com/questions/21165207/search-youtube-api-using-proxy-per-connection-and-not-system-wide for more detail.
Thanks in advance.
thank you, very useful article
Thanks a lot, but for some reason when I work with the jars of your downloaded project works fine, but when I donwnload myself the jars (the same versions ) I get this error :
java.lang.NoSuchMethodError:
in this line:
YouTubeService service = new YouTubeService(clientID);
Exception in thread “main” com.google.gdata.util.NoLongerAvailableException: No longer available
GData
NoLongerAvailableException
No longer availableat com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:617)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:563)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:550)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:530)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
at com.google.gdata.client.Service.getFeed(Service.java:1077)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:662)
at com.google.gdata.client.Service.query(Service.java:1237)
at com.google.gdata.client.Service.query(Service.java:1178)
at com.tusk.controller.YouTubeManager.retrieveVideos(YouTubeManager.java:39)
at com.tusk.controller.YouTubeTester.main(YouTubeTester.java:18)
i have few youtube videos in my android app i wanna give download feature also in that , how shud i do that plz help..