⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 youtubeclient.java

📁 google的gdata api包
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
  /**   * Reads a line of text from the standard input, and returns the parsed   * integer representation.   * @throws IOException if unable to read a line from the standard input   * @return an integer read from the standard input   */  private static int readInt() throws IOException {    String input = readLine();    return Integer.parseInt(input);  }  private static void printUsage() {    System.out.println("Choose one of the following demo options:");    System.out.println("\t1) Print Standard Feeds");    System.out.println("\t2) Print Search Feed");    System.out.println("\t3) Print Keyword Search Feed");    System.out.println("\t4) Print Uploads Feed");    System.out.println("\t5) Print Favorites Feed");    System.out        .println("\t6) Show Comments and Responses Feed for a single Video");    System.out.println("\t7) Print Playlists Feed");    System.out.println("\t8) Display a playlist");    System.out.println("\t9) Print Subscriptions Feed");    System.out.println("\t10) Print User Profile Feed");    System.out.println("\t0) Exit");    System.out.println("\nEnter Number (0-10): ");  }  /**   * Fetchs a user's profile feed and prints out most of the attributes.   *   * @param service a YouTubeService object.   * @throws ServiceException   *                     If the service is unable to handle the request.   * @throws IOException error sending request or reading the feed.   */  private static void printUserProfile(YouTubeService service)      throws IOException, ServiceException {    String testUser = promptForUser();    printUnderlined("User Profile for '" + testUser + "'");    UserProfileEntry userProfileEntry = service.getEntry(new URL(        USER_FEED_PREFIX + testUser), UserProfileEntry.class);    System.out.println("Username: " + userProfileEntry.getUsername());    System.out.println("Age     : " + userProfileEntry.getAge());    System.out.println("Gender  : " + userProfileEntry.getGender());    System.out.println("Single? : " + userProfileEntry.getRelationship());    System.out.println("Books   : " + userProfileEntry.getBooks());    System.out.println("Company : " + userProfileEntry.getCompany());    System.out.println("Describe: " + userProfileEntry.getDescription());    System.out.println("Hobbies : " + userProfileEntry.getHobbies());    System.out.println("Hometown: " + userProfileEntry.getHometown());    System.out.println("Location: " + userProfileEntry.getLocation());    System.out.println("Movies  : " + userProfileEntry.getMovies());    System.out.println("Music   : " + userProfileEntry.getMusic());    System.out.println("Job     : " + userProfileEntry.getOccupation());    System.out.println("School  : " + userProfileEntry.getSchool());  }  /**   * Prints a user's playlists feed.   *   * @param service              a YouTubeService object.   * @param showPlaylistContents if true, print only the first playlist,   *                             followed by all of its contained entries   * @throws ServiceException   *                     If the service is unable to handle the request.   * @throws IOException error sending request or reading the feed.   */  private static void printPlaylists(YouTubeService service,      boolean showPlaylistContents) throws IOException, ServiceException {    String testUser = promptForUser();    printPlaylistsFeed(service, USER_FEED_PREFIX + testUser        + PLAYLISTS_FEED_SUFFIX, showPlaylistContents);  }  /**   * Prints a user's subscriptions feed.   *    * @param service a YouTubeService object.   * @throws ServiceException If the service is unable to handle the request.   * @throws IOException error sending request or reading the feed.   */  private static void printSubscriptions(YouTubeService service)      throws IOException, ServiceException {    String testUser = promptForUser();    printSubscriptionsFeed(service, USER_FEED_PREFIX + testUser         + SUBSCRIPTIONS_FEED_SUFFIX);  }  /**   * Prints a user's favorites feed.   *   * @param service a YouTubeService object.   * @throws ServiceException   *                     If the service is unable to handle the request.   * @throws IOException error sending request or reading the feed.   */  private static void printFavorites(YouTubeService service)      throws IOException, ServiceException {    String testUser = promptForUser();    printVideoFeed(service, USER_FEED_PREFIX + testUser + FAVORITES_FEED_SUFFIX,         false);  }  /**   * Prints a user's uploads feed.   *   * @param service                  a YouTubeService object.   * @param showCommentsAndResponses whether or not to just print the first   *                                 entry, followed by comments and responses   * @throws ServiceException   *                     If the service is unable to handle the request.   * @throws IOException error sending request or reading the feed.   */  private static void printUploads(YouTubeService service,      boolean showCommentsAndResponses) throws IOException, ServiceException {    String testUser = promptForUser();    printVideoFeed(service, USER_FEED_PREFIX + testUser + UPLOADS_FEED_SUFFIX,        showCommentsAndResponses);  }  /**   * Prompts the user to enter his user name on the standard input.   * @return a username entered by the user   * @throws java.io.IOException if unable to read a line from standard input   */  private static String promptForUser() throws IOException {    System.out.println("\nEnter YouTube username [default " + defaultTestUser         + "]: ");    String line = readLine();    if (line == null || "".equals(line.trim())) {      line = defaultTestUser;    } else {      defaultTestUser = line;    }    return line;  }  /**   * Fetches a feed known to be a VideoFeed, printing each VideoEntry with in   * a numbered list, optionally prompting the user for the number of a video   * entry which should have its comments and responses printed.   *   * @param service a YouTubeService object   * @param feedUrl the url of the video feed to print   * @param showCommentsAndResponses true if the user should be prompted for   *                                 a video whose comments and responses should   *                                 printed   * @throws ServiceException   *                     If the service is unable to handle the request.   * @throws IOException error sending request or reading the feed.   */  private static void printVideoFeed(YouTubeService service, String feedUrl,       boolean showCommentsAndResponses) throws IOException, ServiceException {    VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);    String title = videoFeed.getTitle().getPlainText();    if (showCommentsAndResponses) {      title += " with comments and responses";    }    printUnderlined(title);    List<VideoEntry> videoEntries = videoFeed.getEntries();    if (videoEntries.size() == 0) {      System.out.println("This feed contains no entries.");      return;    }    int count = 1;    for (VideoEntry ve : videoEntries) {      printVideoEntry("(Video #" + String.valueOf(count) + ")", ve, false);      count++;    }    if (showCommentsAndResponses) {      System.out.printf(          "\nWhich video to show comments and responses for? (1-%d): \n",           count - 1);      int whichVideo = readInt();      printVideoEntry("", videoEntries.get(whichVideo - 1), true);    }    System.out.println();  }  /**   * Prints a user's playlists feed.   *   * @param service              a YouTubeService object   * @param feedUrl              the url of the feed   * @param showPlaylistContents true if only one entry should be shown,   *                             followed by the contents of the playlist   * @throws ServiceException   *                     If the service is unable to handle the request.   * @throws IOException error sending request or reading the feed.   */  private static void printPlaylistsFeed(YouTubeService service, String feedUrl,       boolean showPlaylistContents) throws IOException, ServiceException {    PlaylistLinkFeed playlistLinkFeed = service.getFeed(new URL(feedUrl),        PlaylistLinkFeed.class);    String title = playlistLinkFeed.getTitle().getPlainText();    if (showPlaylistContents) {      title += " with playlist content.";    }    printUnderlined(title);    List<PlaylistLinkEntry> playlistEntries = playlistLinkFeed.getEntries();    int count = 1;    for (PlaylistLinkEntry pe : playlistEntries) {      printPlaylistEntry("(Playlist #" + count + ")", pe, false);      count++;    }    if (showPlaylistContents) {      System.out.printf("\nWhich playlist do you want to see? (1-%d): \n",          count - 1);      int whichVideo = readInt();      printPlaylistEntry("", playlistEntries.get(whichVideo - 1), true);    }    System.out.println();  }  /**   * Prints a user's subscriptions feed.   *    * @param service a YouTubeService object   * @param feedUrl the url of the feed   * @throws ServiceException If the service is unable to handle the request.   * @throws IOException error sending request or reading the feed.   */  private static void printSubscriptionsFeed(YouTubeService service,      String feedUrl) throws IOException, ServiceException {    SubscriptionFeed subscriptionFeed = service.getFeed(new URL(feedUrl),        SubscriptionFeed.class);    printUnderlined(subscriptionFeed.getTitle().getPlainText());    for (SubscriptionEntry se : subscriptionFeed.getEntries()) {      printSubscriptionEntry(se);    }    System.out.println();  }  /**   * Searches the VIDEOS_FEED for search terms and print each resulting   * VideoEntry.   *   * @param service a YouTubeService object.   * @throws ServiceException   *                     If the service is unable to handle the request.   * @throws IOException error sending request or reading the feed.   */  private static void searchFeed(YouTubeService service)      throws IOException, ServiceException {    YouTubeQuery query = new YouTubeQuery(new URL(VIDEOS_FEED));    // order results by the number of views (most viewed first)    query.setOrderBy(YouTubeQuery.OrderBy.VIEW_COUNT);    // do not exclude restricted content from the search results     // (by default, it is excluded)     query.setIncludeRacy(true);    System.out.println("\nEnter search terms: ");    String searchTerms = readLine();    query.setVideoQuery(searchTerms);    printUnderlined("Running Search for '" + searchTerms + "'");    VideoFeed videoFeed = service.query(query, VideoFeed.class);    for (VideoEntry ve : videoFeed.getEntries()) {      printVideoEntry("", ve, false);    }    System.out.println();  }  /**   * Searches the VIDEOS_FEED for category keywords and prints each resulting   * VideoEntry.   *   * @param service a YouTubeService object.   * @throws ServiceException   *                     If the service is unable to handle the request.   * @throws IOException error sending request or reading the feed.   */  private static void searchFeedWithKeywords(YouTubeService service)      throws IOException, ServiceException {    YouTubeQuery query = new YouTubeQuery(new URL(VIDEOS_FEED));    // order the results by the number of views    query.setOrderBy(YouTubeQuery.OrderBy.VIEW_COUNT);        // include restricted content in the search results    query.setIncludeRacy(true);    // a category filter holds a collection of categories to limit the search    Query.CategoryFilter categoryFilter = new Query.CategoryFilter();    String keywordTerm = null;    String allKeywords = "";    do {      System.out.println("\nEnter keyword or empty line when done: ");      keywordTerm = readLine();      // creates categories whose scheme is KEYWORD_SCHEME      Category category = new Category(YouTubeNamespace.KEYWORD_SCHEME,          keywordTerm);      categoryFilter.addCategory(category);      // keeps track of concatenated list of keywords entered so far      if(!"".equals(keywordTerm))        allKeywords += keywordTerm + ", ";    } while(keywordTerm != null && !"".equals(keywordTerm));    // adds the collection of keyword categories to the query    query.addCategoryFilter(categoryFilter);    printUnderlined("Running Search for '" + allKeywords + "'");    VideoFeed videoFeed = service.query(query, VideoFeed.class);    for (VideoEntry ve : videoFeed.getEntries()) {      printVideoEntry("", ve, false);    }    System.out.println();  }  /**   * YouTubeClient is a sample command line application that demonstrates   * many features of the YouTube data API using the Java Client library.   *   * @param args not used   */  public static void main(String[] args) {    YouTubeService myService = new YouTubeService("gdataSample-YouTube-1");    while (true) {      try {        printUsage();        int choice = readInt();        switch (choice) {          case 1:            // Fetches and prints the standard feeds.            printStandardFeeds(myService);            break;          case 2:            // Searches the VIDEO_FEED for user supplied search terms.            searchFeed(myService);            break;          case 3:            // Searches the VIDEO_FEED for user supplied category keyword terms.            searchFeedWithKeywords(myService);            break;          case 4:            // Fetches and prints a user's uploads feed.            printUploads(myService, false);            break;          case 5:            // Fetches and prints a user's favorites feed.            printFavorites(myService);            break;          case 6:            // Prompts the user for a username and displays the uploads feed            // for that username as a numbered list. The user is asked to choose            // the number of a video entry for which the comments and responses            // feeds should be displayed.            printUploads(myService, true);            break;          case 7:            // Fetches and prints a list of a user's playlists feed.            printPlaylists(myService, false);            break;          case 8:            // Fetches and prints a numbered list of entries in a user's            // playlists feed. The user is then asked to choose the number of            // a playlist he wishes to see the contents of.            printPlaylists(myService, true);            break;          case 9:            // Fetches and prints a user's subscriptions feed.            printSubscriptions(myService);            break;          case 10:            // Fetches and prints a user's profile feed.            printUserProfile(myService);            break;          case 0:          default:            System.exit(0);        }      } catch (IOException e) {          // Communications error          System.err.              println("There was a problem communicating with the service.");          e.printStackTrace();      } catch (ServiceException e) {          // Server side error          System.err.println("The server had a problem handling your request.");          e.printStackTrace();      }    }  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -