使用YouTube API v3从用户名Java获取频道ID

时间:2014-12-16 01:08:27

标签: java youtube youtube-data-api youtube-analytics

我正在尝试将YouTube数据/分析API用于项目,但如果我不拥有它,我不知道如何获取渠道ID。我试图让所有现代音乐家/艺术家的频道分析它们,但似乎无法到达任何地方。

我的代码只是开发者网站的标准代码。见下文。

package com.google.api.services.samples.youtube.cmdline.analytics;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtubeAnalytics.YouTubeAnalytics;
import com.google.api.services.youtubeAnalytics.model.ResultTable;
import com.google.api.services.youtubeAnalytics.model.ResultTable.ColumnHeaders;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.util.List;

/**
 * This example uses the YouTube Data and YouTube Analytics APIs to retrieve
 * YouTube Analytics data. It also uses OAuth 2.0 for authorization.
 *
 * @author Christoph Schwab-Ganser and Jeremy Walker
 */
public class YouTubeAnalyticsReports {

/**
 * Define a global instance of the HTTP transport.
 */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

/**
 * Define a global instance of the JSON factory.
 */
private static final JsonFactory JSON_FACTORY = new JacksonFactory();

/**
 * Define a global instance of a Youtube object, which will be used
 * to make YouTube Data API requests.
 */
private static YouTube youtube;

/**
 * Define a global instance of a YoutubeAnalytics object, which will be
 * used to make YouTube Analytics API requests.
 */
private static YouTubeAnalytics analytics;

/**
 * This code authorizes the user, uses the YouTube Data API to retrieve
 * information about the user's YouTube channel, and then fetches and
 * prints statistics for the user's channel using the YouTube Analytics API.
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {

    // These scopes are required to access information about the
    // authenticated user's YouTube channel as well as Analytics
    // data for that channel.
    List<String> scopes = Lists.newArrayList(
            "https://www.googleapis.com/auth/yt-analytics.readonly",
            "https://www.googleapis.com/auth/youtube.readonly"
    );

    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "analyticsreports");

        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("youtube-analytics-api-report-example")
                .build();

        // This object is used to make YouTube Analytics API requests.
        analytics = new YouTubeAnalytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("youtube-analytics-api-report-example")
                .build();

        // Construct a request to retrieve the current user's channel ID.
        YouTube.Channels.List channelRequest = youtube.channels().list("id,snippet");
        channelRequest.setMine(true);
        channelRequest.setFields("items(id,snippet/title)");
        ChannelListResponse channels = channelRequest.execute();

        // List channels associated with the user.
        List<Channel> listOfChannels = channels.getItems();

        // The user's default channel is the first item in the list.
        Channel defaultChannel = listOfChannels.get(0);
        String channelId = defaultChannel.getId();

        PrintStream writer = System.out;
        if (channelId == null) {
            writer.println("No channel found.");
        } else {
            writer.println("Default Channel: " + defaultChannel.getSnippet().getTitle() +
                    " ( " + channelId + " )\n");

            printData(writer, "Views Over Time.", executeViewsOverTimeQuery(analytics, channelId));
            printData(writer, "Top Videos", executeTopVideosQuery(analytics, channelId));
            printData(writer, "Demographics", executeDemographicsQuery(analytics, channelId));
        }
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

/**
 * Retrieve the views and unique viewers per day for the channel.
 *
 * @param analytics The service object used to access the Analytics API.
 * @param id        The channel ID from which to retrieve data.
 * @return The API response.
 * @throws IOException if an API error occurred.
 */
private static ResultTable executeViewsOverTimeQuery(YouTubeAnalytics analytics,
                                                     String id) throws IOException {

    return analytics.reports()
            .query("channel==" + id,     // channel id
                    "2012-01-01",         // Start date.
                    "2012-01-14",         // End date.
                    "views,uniques")      // Metrics.
            .setDimensions("day")
            .setSort("day")
            .execute();
}

/**
 * Retrieve the channel's 10 most viewed videos in descending order.
 *
 * @param analytics the analytics service object used to access the API.
 * @param id        the string id from which to retrieve data.
 * @return the response from the API.
 * @throws IOException if an API error occurred.
 */
private static ResultTable executeTopVideosQuery(YouTubeAnalytics analytics,
                                                 String id) throws IOException {

    return analytics.reports()
            .query("channel==" + id,                          // channel id
                    "2012-01-01",                              // Start date.
                    "2012-08-14",                              // End date.
                    "views,subscribersGained,subscribersLost") // Metrics.
            .setDimensions("video")
            .setSort("-views")
            .setMaxResults(10)
            .execute();
}

/**
 * Retrieve the demographics report for the channel.
 *
 * @param analytics the analytics service object used to access the API.
 * @param id        the string id from which to retrieve data.
 * @return the response from the API.
 * @throws IOException if an API error occurred.
 */
private static ResultTable executeDemographicsQuery(YouTubeAnalytics analytics,
                                                    String id) throws IOException {
    return analytics.reports()
            .query("channel==" + id,     // channel id
                    "2007-01-01",         // Start date.
                    "2012-08-14",         // End date.
                    "viewerPercentage")   // Metrics.
            .setDimensions("ageGroup,gender")
            .setSort("-viewerPercentage")
            .execute();
}

/**
 * Prints the API response. The channel name is printed along with
 * each column name and all the data in the rows.
 *
 * @param writer  stream to output to
 * @param title   title of the report
 * @param results data returned from the API.
 */
private static void printData(PrintStream writer, String title, ResultTable results) {
    writer.println("Report: " + title);
    if (results.getRows() == null || results.getRows().isEmpty()) {
        writer.println("No results Found.");
    } else {

        // Print column headers.
        for (ColumnHeaders header : results.getColumnHeaders()) {
            writer.printf("%30s", header.getName());
        }
        writer.println();

        // Print actual data.
        for (List<Object> row : results.getRows()) {
            for (int colNum = 0; colNum < results.getColumnHeaders().size(); colNum++) {
                ColumnHeaders header = results.getColumnHeaders().get(colNum);
                Object column = row.get(colNum);
                if ("INTEGER".equals(header.getUnknownKeys().get("dataType"))) {
                    long l = ((BigDecimal) column).longValue();
                    writer.printf("%30d", l);
                } else if ("FLOAT".equals(header.getUnknownKeys().get("dataType"))) {
                    writer.printf("%30f", column);
                } else if ("STRING".equals(header.getUnknownKeys().get("dataType"))) {
                    writer.printf("%30s", column);
                } else {
                    // default output.
                    writer.printf("%30s", column);
                }
            }
            writer.println();
        }
            writer.println();
        }
    }

}

任何指针都会很棒。提前致谢

2 个答案:

答案 0 :(得分:0)

这是我的方法可行,我在我的应用程序中使用它。在此代码段中缺少Helper类,我用它来读取main方法中的开发人员密钥。

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.gdata.data.youtube.UserEventEntry;
import com.google.gdata.data.youtube.UserEventFeed;
import com.google.gdata.util.ServiceException;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 */
public class UserHarvest {

    private String username;

    // all user public channels
    private List<Channel> channels = new ArrayList<>();

    // all user(channel) public activities
    // https://developers.google.com/gdata/javadoc/com/google/gdata/data/youtube/UserEventEntry
    private List<UserEventEntry> activities = new ArrayList<>();

    // Max number of channels we want returned (minimum: 0, default: 5, maximum: 50)
    private long maxNumChannels = 50;

    //<editor-fold defaultstate="collapsed" desc="getters and setters">

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public List<Channel> getChannels() {
        return channels;
    }

    public void setChannels(List<Channel> channels) {
        this.channels = channels;
    }

    public List<UserEventEntry> getActivities() {
        return activities;
    }

    public void setActivities(List<UserEventEntry> activities) {
        this.activities = activities;
    }

    public long getMaxNumChannels() {
        return maxNumChannels;
    }

    public void setMaxNumChannels(long maxNumChannels) {
        this.maxNumChannels = maxNumChannels;
    }

    //</editor-fold>

    public UserHarvest() {
    }

    public UserHarvest(String username) {
        this.username = username;
    }

    /**
     * Fetches a feed of activities and prints information about them.
     *
     * @param userA user name
     * @throws java.io.IOException request exp
     * @throws com.google.gdata.util.ServiceException service exp
     * 
     */
    public void harvestUserActivities(String userA)
            throws IOException, ServiceException {

        UserEventFeed activityFeed = Helper.service.getFeed(new URL("http://gdata.youtube.com/feeds/api/events?author=" + userA),
                UserEventFeed.class);
        String title = activityFeed.getTitle().getPlainText();
        Helper.printUnderlined(title);
        if (activityFeed.getEntries().isEmpty()) {
            System.out.println("This feed contains no entries.");
            this.activities = null;
        }

        List<UserEventEntry> entries = new ArrayList<>();

        for (UserEventEntry entry : activityFeed.getEntries()) {
            entries.add(entry);
        }

        Helper.printUserActivities(activityFeed);

        this.activities = entries;

    }

    /*
     * Harvest users channels
     * 
     * @param channelUsername name of user (channel)
     * 
     */
    public void harvestChannels(String channelUsername) {

        try {
            // https://developers.google.com/resources/api-libraries/documentation/youtube/v3/java/latest/com/google/api/services/youtube/YouTube.Channels.List.html
            YouTube.Channels.List channelRequest = Helper.youtube.channels().list("id,snippet,statistics,contentDetails");
            channelRequest.setKey(Helper.developerKeyV3);
            channelRequest.setFields("items(id,snippet,contentDetails/relatedPlaylists,statistics/videoCount,statistics/commentCount,brandingSettings/channel/title)");
            channelRequest.setForUsername(channelUsername);

            // max result parameter is 50
            if (maxNumChannels > 50)
                channelRequest.setMaxResults((long)50);
            else
                channelRequest.setMaxResults(maxNumChannels);

            ChannelListResponse channelResponse = channelRequest.execute();
            this.channels = channelResponse.getItems();

            String nextToken = "";

            // Loops over next channel page results
            while (this.channels.size() < this.maxNumChannels) {
              channelRequest.setPageToken(nextToken);
              ChannelListResponse nextChannelResponse = channelRequest.execute();

              this.channels.addAll(nextChannelResponse.getItems());

              if (this.channels.size() > this.maxNumChannels){
                  this.channels = this.channels.subList(0, (int)this.maxNumChannels-1);
                  break;
              }

              nextToken = nextChannelResponse.getNextPageToken();

              if (nextToken == null)
                  break;

            } 

            Helper.prettyPrintObjects(this.channels.iterator(), "Channel");

        } catch (GoogleJsonResponseException e) {
            System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
                    + e.getDetails().getMessage());

        } catch (IOException e) {
            System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        }

    }

    // main method for testing purposes
    public static void main(String[] args) {

        Helper.readDeveloperKeys();

        //https://www.youtube.com/user/nqtv

        UserHarvest usrHarvest = new UserHarvest("nqtv");

        // Youtube API v2
        try {

            usrHarvest.harvestUserActivities("nqtv");

        } catch (IOException ex) {
            Logger.getLogger(VideoHarvest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ServiceException ex) {
            Logger.getLogger(VideoHarvest.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Youtube API v3
        try {

            Helper.youtube = new YouTube.Builder(Helper.HTTP_TRANSPORT, Helper.JSON_FACTORY, new HttpRequestInitializer() {
                public void initialize(HttpRequest request) throws IOException {
                }
            }).setApplicationName(Helper.APPLICATION_NAME).build();

            //https://www.youtube.com/user/nqtv                

            usrHarvest.harvestChannels("nqtv");

        } catch (Throwable t) {
            t.printStackTrace();
        }

    }
}

答案 1 :(得分:0)

您可以查看以下链接:https://github.com/youtube/api-samples 您可以在此下载api-samples,您将找到一个搜索示例,然后更改下面提到的代码,这将有助于您获取频道。希望这对您有所帮助。

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.ResourceId;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import com.google.api.services.youtube.model.Thumbnail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;


public class Search {

  private static String PROPERTIES_FILENAME = "youtube.properties";

  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  private static final JsonFactory JSON_FACTORY = new JacksonFactory();

  private static final long NUMBER_OF_VIDEOS_RETURNED = 50;

  private static YouTube youtube;

  public static void main(String[] args) {
    // Read the developer key from youtube.properties
    Properties properties = new Properties();
    try {
      InputStream in = Search.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
      properties.load(in);

    } catch (IOException e) {
      System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause()
          + " : " + e.getMessage());
      System.exit(1);
    }

    try {
      youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) throws IOException {}
      }).setApplicationName("youtube-cmdline-search-sample").build();

      // Get query term from user.
      String queryTerm = getInputQuery();

      YouTube.Search.List search = youtube.search().list("id,snippet");

      String apiKey = properties.getProperty("youtube.apikey");
      search.setKey(apiKey);
      search.setQ(queryTerm);

      search.setType("video");


      search.setFields("items(id/kind,id/videoId,snippet/title,snippet/publishedAt,snippet/description,snippet/channelId,snippet/thumbnails/default/url)");
      search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
      SearchListResponse searchResponse = search.execute();

      List<SearchResult> searchResultList = searchResponse.getItems();

      if (searchResultList != null) {
        prettyPrint(searchResultList.iterator(), queryTerm);
        BufferedReader bRead = new BufferedReader(new InputStreamReader(System.in));

      }
    } catch (GoogleJsonResponseException e) {
      System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
          + e.getDetails().getMessage());
    } catch (IOException e) {
      System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }

  /*
   * Returns a query term (String) from user via the terminal.
   */
  private static String getInputQuery() throws IOException {

    String inputQuery = "";

    System.out.print("Please enter a search term: ");
    BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
    inputQuery = bReader.readLine();

    if (inputQuery.length() < 1) {
      // If nothing is entered, defaults to "YouTube Developers Live."
      inputQuery = "YouTube Developers Live";
    }
    return inputQuery;
  }


  private static void prettyPrint(Iterator<SearchResult> iteratorSearchResults, String query) {

    System.out.println("\n=============================================================");
    System.out.println(
        "   First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\".");
    System.out.println("=============================================================\n");

    ArrayList <String> videoid = new ArrayList<String>();
    ArrayList <String> videotitle = new ArrayList<String>();
    ArrayList <String> videothumnail = new ArrayList<String>();
    ArrayList <String> publishedAt= new ArrayList<String>();
    ArrayList <String> channelId = new ArrayList<String>();
    ArrayList <String> description = new ArrayList<String>();

    if (!iteratorSearchResults.hasNext()) {
      System.out.println(" There aren't any results for your query.");
    }

    while (iteratorSearchResults.hasNext()) {

      SearchResult singleVideo = iteratorSearchResults.next();
      ResourceId rId = singleVideo.getId();


      // Double checks the kind is video.
      if (rId.getKind().equals("youtube#video")) {
        Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().get("default");

        videoid.add(rId.getVideoId());
        videotitle.add(singleVideo.getSnippet().getTitle());
        description.add(singleVideo.getSnippet().getDescription());
        videothumnail.add(thumbnail.getUrl());
        publishedAt.add(singleVideo.getSnippet().getPublishedAt().toString());
        channelId.add(singleVideo.getSnippet().getChannelId());


      }

    }
        System.out.println(videoid);
        System.out.println(videotitle);
        System.out.println(videothumnail);
        System.out.println(publishedAt);
        System.out.println(description);
        System.out.println(channelId);

  }
}