【发布时间】: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