使用服务器令牌连接到YouTube API

时间:2020-02-02 23:27:36

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

我正在成功使用以下代码连接到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帐户。

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

1 个答案:

答案 0 :(得分:1)

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

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