public static Credential authorize(final NetHttpTransport httpTransport) throws IOException {
InputStream in = new FileInputStream(CLIENT_SECRETS);
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
.setAccessType("offline")
.build();
int defaultPort = 5005;
LocalServerReceiver customReceiver = new LocalServerReceiver.Builder()
.setHost("localhost")
.setPort(defaultPort)
.build();
Credential credential = new AuthorizationCodeInstalledApp(flow, customReceiver).authorize("userid");
return credential;
}
public static YouTube getService() throws GeneralSecurityException, IOException {
final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
Credential credential = authorize(httpTransport);
return new YouTube.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
所以一切都适合我,但我每次都需要登录,但我不想这样做。是否可以修改代码或其他任何内容,以便使用给定的电子邮件和密码自动执行此操作?
如果配置正确,客户端库将处理用户令牌存储。
您忘记配置
setDataStoreFactory
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
我的 TOKENS_DIRECTORY_PATH 只是设置为令牌,然后将它们存储在当前目录中。
private static final String TOKENS_DIRECTORY_PATH = "tokens";