I am trying to write a program for listing the files in my Google Drive using the Google Drive API.
I have created a service account for my account.
Here is the service object that I have created
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;
}
using this service object I called the 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;
}
but this is returning an empty Items array
{"etag":"\"8M2pZwE_fwroB5BIq5aUjc3uhqg/vyGp6PvFo4RvsFtPoIWeCReyIC8\"",
"kind":"drive#fileList","selfLink":"https://www.googleapis.com/drive/v2/files",
"items":[]}
Can someone please help me with this, am I missing something?
Thanks.
You are using an application-owned account which is like a regular account but belonging to an app instead of an user.
Application-owned accounts don't have special permissions and, as regular accounts, can only access documents they own or that were shared with them. Therefore, if your regular account owns the files, the service account will not be able to list them.
You can use domain-wide delegation to allow your app to access files on behalf of other users in a Google Apps domain:
https://developers.google.com/drive/delegation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With