使用服务帐户访问Google Drive API

时间:2016-07-28 02:32:14

标签: google-api google-drive-api google-api-client google-api-java-client

我尝试使用服务帐户访问Google Drive API。我已经设置了服务帐户来访问Google Directory API,我认为我可以使用相同的服务帐户。这是我的代码,它几乎是不言自明的。

exec()

但是,我得到了#com; go.google.api.client.auth.oauth2.TokenResponseException:401 Unauthorized&#34;在 private static List<File> retrieveAllFiles(Drive service) throws IOException { List<File> result = new ArrayList<File>(); Files.List request = service.files().list(); do { FileList files = request.execute(); result.addAll(files.getItems()); request.setPageToken(files.getNextPageToken()); } while (request.getPageToken() != null && request.getPageToken().length() > 0); return result; } public static Drive getDriveService(){ GoogleDriectoryService GDservice = new GoogleDriectoryService(); java.io.File serviceAccountP12Certificate = GDservice.loadF("resources/APIProject-62d885cdf671.p12"); HttpTransport httpTransport = new NetHttpTransport();//? JacksonFactory jsonFactory = new JacksonFactory();//? GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(jsonFactory) .setServiceAccountId(serviceAccountEmailAddress) .setServiceAccountScopes(Arrays.asList(DriveScopes.DRIVE)) .setServiceAccountUser(serviceAccountUser) .setServiceAccountPrivateKeyFromP12File(serviceAccountP12Certificate) .build(); Drive service = new Drive.Builder(httpTransport, jsonFactory, credential) .setApplicationName("radiantlogic-vds").build(); return service; } public static void main(String[] args){ Drive service = getDriveService(); List<File> files = retrieveAllFiles(service); System.out.println(files); } 行。任何帮助表示赞赏。

0 个答案:

没有答案