Ilias Tsagklis

About Ilias Tsagklis

Ilias Tsagklis is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services. Ilias is co-founder and Executive Editor at Java Code Geeks.

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.

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!

Related Articles :
Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

10 Responses to "Getting Started with YouTube Java API"

  1. Thank you very very much!

  2. ashutosh says:

    I need help with rtsp link …please help.

  3. biswajit says:

    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)

  4. Farzad says:

    It works on Eclipes but netbeans throws an exception NoSuchMethodError

  5. Dwaraka says:

    thank u..I m done with this…I m working on project of developing youtube webcrawler..
    So ,I need to know further steps..

  6. Sansuns says:

    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)

  7. hemratna says:

    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.

  8. dariusiv says:

    thank you, very useful article

Leave a Reply


+ 3 = four



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.