【发布时间】:2018-05-02 16:05:27
【问题描述】:
我正在尝试在我的动态网络应用项目中通过 youtube API 获取 youtube 视频 cmets。
我的代码:
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下
【问题讨论】:
-
可能范围为空。你试过保护这个变量吗?
-
@TalAvissar“保护这个变量”?你是什么意思&请阅读下面的答案评论
标签: java json youtube-api youtube-data-api