【问题标题】:how to call client_secrets.json from an external directory java?如何从外部目录 java 调用 client_secrets.json?
【发布时间】:2023-04-03 03:13:02
【问题描述】:

我基本上有一个动态 WEB-APP,它通过一个 servlet 我试图检索一个 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);
}

有了这个,我在以下行得到了 nullpointerexception:Credential credential = Auth.authorize(scopes, "commentthreads");

如果你能解释一下scope 是什么,你从哪里得到它。

第二次尝试我尝试创建一个不同的函数来获取凭据。

第二次尝试:

   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 {

    // Load client secrets.
    Reader clientSecretReader = new InputStreamReader(
            Auth.class.getResourceAsStream("/home/hazrat/Documents/eclipse-jee-neon-3-linux-gtk-x86_64/eclipse/client_secrets.json"));
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);

    // Checks that the defaults have been replaced (Default = "Enter X here").
    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;
    }

    // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
    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();

    // Build the local server and bind it to port 8080
    LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

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

我在Reader clientSecretReader = new InputStreamReader(... 行也收到了一个空指针异常,但如果我在终端中尝试nano /home/hazrat/Documents/eclipse-jee-neon-3-linux-gtk-x86_64/eclipse/client_secrets.json,我可以访问该文件。

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

【问题讨论】:

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


    【解决方案1】:

    有点痛苦,但让第二个解决方案奏效了。

    所以我做错了,我调用了Auth.class.getResourceAsStream,它要求classLoader 可以使用数据,但我的classLoader 却没有。

    所以我要做的是从外部目录请求我的 client_secrets.json,然后你必须使用 FileInputStream 而不是 getResourceAsStream

    FileInputStreamgetResourceAsStream 都可以正常工作,但它们因您的情况和不同的代码而异。

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

    注意:FileInputStream位置更改为您自己的位置。

    然后您可以致电getYoutubeOauth 并希望得到有效的回复:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 2022-06-13
      • 2013-02-06
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多