如何从外部java目录调用client_secrets.json?

如何从外部java目录调用client_secrets.json?,java,json,youtube-api,youtube-data-api,Java,Json,Youtube Api,Youtube Data Api,我基本上有一个动态WEB应用程序,通过servlet我试图检索youtube视频评论 虽然网上有很多关于它的文章,但我不知道为什么没有一篇适合我 第一次尝试: private static int counter = 0; private static YouTube youtube; public static void getYoutubeOauth() throws Exception { List<String> scopes = Lists.newArrayLis

我基本上有一个动态WEB应用程序,通过servlet我试图检索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);
}
这里我在
Reader-clientSecretReader=new-InputStreamReader(…
第行得到一个nullpointerexception,尽管如果我尝试
nano/home/hazrat/Documents/eclipse-jee-neon-3-linux-gtk-x86_64/eclipse/client_secrets.json,我可以在终端中访问该文件


问题:如何授权我的web应用程序并从外部目录读取client_secrets.json。

有点痛苦,但第二个解决方案起了作用

所以我做错了,我调用了
Auth.class.getResourceAsStream
,它要求数据对
classLoader
可用,但对我的classLoader不可用

因此,我必须做的是从外部目录请求我的客户机_secrets.json,然后您必须使用
FileInputStream
而不是
getResourceAsStream

FileInputStream
getResourceAsStream
都可以正常工作,但它们根据您的情况和不同的代码而有所不同

public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final String CREDENTIALS_DIRECTORY = ".oauth-credentials";

public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {
    Reader clientSecretReader = new InputStreamReader(
            new FileInputStream("/client_secrets.json"));
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);
    System.out.println(clientSecretReader.toString());
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        System.out.println(
                "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
                        + "into src/main/resources/client_secrets.json");
        return null;
    }
    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
    DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
            .build();
    LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8081).build();

    return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
}

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 = 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;

        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();
    }
}
public static final HttpTransport HTTP_TRANSPORT=new NetHttpTransport();
公共静态最终JsonFactory JSON_FACTORY=new JacksonFactory();
私有静态最终字符串凭据\u目录=“.oauth凭据”;
公共静态凭据授权(列表作用域、字符串credentialDatastore)引发IOException{
Reader clientSecretReader=新的InputStreamReader(
新文件输入流(“/client_secrets.json”);
GoogleClientSecrets clientSecrets=GoogleClientSecrets.load(JSON_工厂,clientSecretReader);
System.out.println(clientSecretReader.toString());
if(clientSecrets.getDetails().getClientId().startsWith(“输入”)
||clientSecrets.getDetails().getClientSecret().startsWith(“输入”)){
System.out.println(
“从中输入客户端ID和密码https://console.developers.google.com/project/_/apiui/credential "
+“输入src/main/resources/client_secrets.json”);
返回null;
}
FileDataStoreFactory FileDataStoreFactory=newfiledatastorefactory(新文件(System.getProperty(“user.home”)+“/”+CREDENTIALS_目录));
DataStore DataStore=fileDataStoreFactory.getDataStore(credentialDatastore);
GoogleAuthorizationCodeFlow=新建GoogleAuthorizationCodeFlow.Builder(
HTTP_传输、JSON_工厂、clientSecrets、scopes)。setCredentialDataStore(数据存储)
.build();
LocalServerReceiver localReceiver=新的LocalServerReceiver.Builder().setPort(8081.build();
返回新的AuthorizationCodeInstalledApp(流,localReceiver)。授权(“用户”);
}
专用静态整数计数器=0;
私有静态YouTube YouTube;
public static void getyoutubeauth()引发异常{
列表范围=列表。newArrayList(“https://www.googleapis.com/auth/youtube.force-ssl");
凭证=授权(作用域,“评论线程”);
youtube=new youtube.Builder(Auth.HTTP_TRANSPORT,Auth.JSON_FACTORY,credential).build();
字符串videoId=“KIgxmV9xXBQ”;
//获取视频评论线程
CommentThreadListResponse commentsPage=prepareListRequest(videoId).execute();
while(true){
handleCommentsThreads(commentsPage.getItems());
String nextPageToken=commentsPage.getNextPageToken();
if(nextPageToken==null)
打破
commentsPage=prepareListRequest(videoId).setPageToken(nextPageToken.execute();
}
系统输出打印项次(“总计:+计数器);
}
私有静态YouTube.CommentThreads.List prepareListRequest(字符串videoId)引发异常{
返回youtube.commentThreads()
.list(“片段、回复”)
.setVideoId(videoId)
.setMaxResults(100L)
.setModerationStatus(“已发布”)
.setTextFormat(“纯文本”);
}
私有静态void handleCommentsThreads(列出commentThreads){
for(CommentThread CommentThread:commentThreads){
List comments=Lists.newArrayList();
comments.add(commentThread.getSnippet().getTopLevel注释());
CommentThreadReplies=commentThread.getReplies();
如果(回复!=null)
comments.addAll(repress.getComments());
System.out.println(“find”+comments.size()+comments.”);
//你的评论符合逻辑吗
计数器+=注释.size();
}
}
注意:
FileInputStream
位置更改为您自己的位置

然后您可以调用
getYoutubeOauth
,希望得到一个有效的响应:)

public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final String CREDENTIALS_DIRECTORY = ".oauth-credentials";

public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {
    Reader clientSecretReader = new InputStreamReader(
            new FileInputStream("/client_secrets.json"));
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);
    System.out.println(clientSecretReader.toString());
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        System.out.println(
                "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
                        + "into src/main/resources/client_secrets.json");
        return null;
    }
    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
    DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
            .build();
    LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8081).build();

    return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
}

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 = 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;

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