java - 使用 YouTube API v3 从用户名 Java 获取 channel ID

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

我正在尝试在项目中使用 YouTube 数据/分析 API,但如果我不拥有 channel ID,我不知道如何获取该 channel ID。我试图让所有现代音乐家/艺术家的 channel 来分析它们,但似乎无济于事。

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

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();
        }
    }

}

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

最佳答案

这是我的方法,它有效,我在我的应用程序中使用它。在此代码片段中缺少 Helper 类,我用它来读取主方法中的开发人员 key 。

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();
        }

    }
}

关于java - 使用 YouTube API v3 从用户名 Java 获取 channel ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27495942/

相关文章:

java - 膨胀二进制 XML 文件时出错

java - Struts 2(版本 2.3.28)只接受注册语言环境

java - 如何让我的 .bat 文件运行 java 命令

jquery - Vimeo 全屏不适用于 jquery colorbox

python - QwebView 不播放 Youtube 视频

youtube - Google API - 服务器 key 和浏览器 key 的有效性?

youtube - 检索播放列表中包含的视频 ID - YouTube API v3

java - for循环中的Findviewbyid()

youtube - 无法在 YouTube 嵌入中使用 "showinfo=0"

jquery - 网站中的 Youtube 设备支持消息