我正在尝试编写一个程序来使用 Google Drive API 列出我的 Google Drive 中的文件。
我为我的帐户创建了一个服务帐户。
这是我创建的服务对象
public static Drive getDriveService() throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(
"https://www.googleapis.com/auth/drive")
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setApplicationName("FileListAccessProject")
.setHttpRequestInitializer(credential).build();
return service;
}
使用这个服务对象,我调用了 file.list
private static List<File> retrieveAllFiles(Drive service)
throws IOException {
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try {
FileList files = request.execute();
System.out.println(files);
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null
&& request.getPageToken().length() > 0);
// System.out.println(result);
return result;
}
但这是返回一个空的 Items 数组
{"etag":"\"8M2pZwE_fwroB5BIq5aUjc3uhqg/vyGp6PvFo4RvsFtPoIWeCReyIC8\"",
"kind":"drive#fileList","selfLink":"https://www.googleapis.com/drive/v2/files",
"items":[]}
有人可以帮我解决这个问题,我错过了什么吗?
谢谢。