【问题标题】:Connect to YouTube API using Server token使用服务器令牌连接到 YouTube API
【发布时间】:2020-05-18 18:10:35
【问题描述】:

我正在成功使用以下代码连接到 YouTube API:

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 {

    InputStream in = GoogleSheetImpl.class.getResourceAsStream("/client_secret_json");

    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
    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(8080).build();
    return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
}

private static YouTube youtube;

@Test
public void test() {

    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl");

    try {
        Credential credential = authorize(scopes, "commentthreads");

        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("youtube-cmdline-playlistupdates-sample")
                .build();

        process();

    } catch (GoogleJsonResponseException e) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

但正如您所见,它使用 OAuth 来验证打开网页并要求我登录到我的 Google 帐户。

有没有办法使用服务器到服务器令牌?对于令牌,我不需要加载网页来进行身份验证。是否有一些教程如何正确配置连接工厂?

【问题讨论】:

    标签: java youtube-api youtube-data-api google-api-java-client


    【解决方案1】:

    并非所有 Google api 都支持服务帐号。 YouTube api 是不支持服务帐户身份验证的 API 之一。

    您需要使用 Oauth2 对用户进行身份验证,然后保存刷新令牌,然后您可以使用该刷新令牌请求新的访问令牌。

    【讨论】:

    • 有什么方法可以在不打开网页和每次登录用户的情况下使用 API?我需要一种方法来从 Linux 服务器上进行来自不同用户的多次调用。我没有打开网页的选项。
    • 是的,您按照我的说明进行操作并在存储刷新令牌后对其进行身份验证(使用您的代码将其上传到服务器),然后您将能够使用刷新令牌来请求新的访问令牌你需要。只要您拥有该刷新令牌,就不需要再次对其进行身份验证。
    • 我发现了一个阻塞问题。我可以在 Google 登录页面中验证最多 10 个帐户。有什么方法可以验证更多吗?
    • 您使用服务帐户而不是谷歌登录这不会影响您。
    • 这是主要问题 -> 我无法使用 YouTube Java Api 的服务帐户,因为仅支持通过 Web 界面登录。我找不到通过刷新令牌使用登录的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2017-10-28
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 2020-08-13
    相关资源
    最近更新 更多