访问令牌和刷新令牌在Google服务帐户中的驱动器api中为空
问题描述:
我在运行我的代码时将访问令牌和刷新令牌设为null。没有编译错误。我不明白为什么会发生这种情况。 plz帮助。访问令牌和刷新令牌在Google服务帐户中的驱动器api中为空
我正在从官方网站提供的示例中查看此示例。
其实,我想做服务器到服务器授权,可以使用服务帐户在谷歌驱动器完成。我甚至不想向用户显示同意屏幕。我下面谷歌驱动器文档,这是在
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
我的代码是:
public class TFT {
private static final String ApplicationName = "Boston";
private static final String serviceAccountEmailAddress = "[email protected]";
private static final String serviceAccountUser = "[email protected]";
private static List<File> retrieveAllFiles(Drive service) throws IOException {
List<File> result = new ArrayList<>();
Files.List request = service.files().list();
do {
FileList files = request.execute();
result.addAll(files.getFiles());
request.setPageToken(files.getNextPageToken());
} while (request.getPageToken() != null && request.getPageToken().length() > 0);
return result;
}
public static Drive getDriveService() throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = null;
try {
credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(serviceAccountEmailAddress)
.setServiceAccountScopes(DriveScopes.all())
.setServiceAccountUser(serviceAccountUser)
.setServiceAccountPrivateKeyFromP12File(new java.io.File("/home/xpointers/Downloads/Boston-2b55ddf4a5c8.p12"))
.build();
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName(ApplicationName)
.build();
return service;
}
private java.io.File getp12File(String fileName) {
ClassLoader classLoader = getClass().getClassLoader();
return new java.io.File(classLoader.getResource(fileName).getFile());
}
public static void main(String[] args) {
try {
Drive service = getDriveService();
List<File> files;
files = retrieveAllFiles(service);
System.out.println(files);
} catch (IOException e) {
e.printStackTrace();
}
}
}
答
你可以参考这个thread这表明使用credential.refreshToken();
。
我们需要调用
credential.refreshToken();
然后String token=credential.getAccessToken();
参考文献:
你的链接对我有点帮助。谢谢。需要知道一件事,你能告诉我从我应该采取的服务AccountAccountEmailAddress和serviceAccountUser – Vivek