如何在YouTube API中调用client_secrets.json



我正在尝试通过youtube API在我的动态Web应用程序项目上获取YouTube视频评论。

我的代码:

private static int counter = 0;
private static YouTube youtube;
public static void getYoutubeOauth() throws Exception {
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl");
    Credential credential = Auth.authorize(scopes, "commentthreads");
    youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).build();
    String videoId = "KIgxmV9xXBQ";
    // Get video comments threads
    CommentThreadListResponse commentsPage = prepareListRequest(videoId).execute();
    while (true) {
        handleCommentsThreads(commentsPage.getItems());
        String nextPageToken = commentsPage.getNextPageToken();
        if (nextPageToken == null)
            break;
        // Get next page of video comments threads
        commentsPage = prepareListRequest(videoId).setPageToken(nextPageToken).execute();
    }
    System.out.println("Total: " + counter);
}
private static YouTube.CommentThreads.List prepareListRequest(String videoId) throws Exception {
    return youtube.commentThreads()
                  .list("snippet,replies")
                  .setVideoId(videoId)
                  .setMaxResults(100L)
                  .setModerationStatus("published")
                  .setTextFormat("plainText");
}
private static void handleCommentsThreads(List<CommentThread> commentThreads) {
    for (CommentThread commentThread : commentThreads) {
        List<Comment> comments = Lists.newArrayList();
        comments.add(commentThread.getSnippet().getTopLevelComment());
        CommentThreadReplies replies = commentThread.getReplies();
        if (replies != null)
            comments.addAll(replies.getComments());
        System.out.println("Found " + comments.size() + " comments.");
        // Do your comments logic here
        counter += comments.size();
    }
}

在执行上面的代码时,我在第 Credential credential = Auth.authorize(scopes, "commentthreads"); 行得到一个java.lang.NullPointerException

仅供参考:我知道NullPointerException是什么,即string n = null; if(n=="h"); NullPointerException的原因

我希望client_secrets.json文件可以抵消原因,因为我不知道在哪里放置以及如何在我的代码中调用它。

我当前client_secrets.json被置于/home/UserName/workspace/RemoteSystemsTempFiles/Duck/WebContent/WEB-INF/client_secrets.json

可以按如下方式加载客户端机密 json 文件:

// Load client secrets.
Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/client_secrets.json"));
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);

有关如何将身份验证与Google API一起使用的更多信息,请查看此处

相关内容

  • 没有找到相关文章

最新更新