Google云端硬盘服务帐户-文件列表仅返回名为“入门”的文件

时间:2019-01-30 00:53:18

标签: google-drive-api

我参与了一个内部应用程序的构建,通过它可以下载公司Google云端硬盘帐户中存储的最新修改文件。

我使用了与该API项目相关联的服务帐户来生成密钥,该密钥作为原始资源包含在我们的项目中,以便使用OAuth2进行身份验证以获取GoogleCredential,这是构建用于创建API的Drive服务所必需的电话。

经过身份验证后,我尝试列出文件以获取其ID,但是,我在Google云端硬盘帐户中看不到文件,响应仅返回一个名为“入门”的文件。

为服务帐户创建了一个密钥,为JSON格式。

我让我的系统管理员执行了此处详述的步骤,以委派Drive API访问服务帐户的权限:https://developers.google.com/drive/v2/web/delegation#delegate_domain-wide_authority_to_your_service_account

我已经编写了一个代码,该代码将创建一个DriveService实例,该实例可以直接列出到服务帐户,并引用JSON文件中的服务帐户密钥:

private static GoogleCredential getCredential() throws IOException {
        final InputStream stream = DriveServiceAccount.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        final GoogleCredential credential = GoogleCredential.fromStream(stream)
          .createScoped(Collections.singleton(DriveScopes.DRIVE));

    return credential.createScoped(Collections.singleton(DriveScopes.DRIVE));
}

private static List<File> retrieveAllFiles(final Drive service) throws IOException {
    final List<File> result = new ArrayList<>();

    String pageToken = null;
    do {
      FileList files = service.files().list()
        .setFields("nextPageToken, files(id, name)")
        .setPageToken(pageToken)
        .execute();

      result.addAll(files.getFiles());

      pageToken = files.getNextPageToken();
    } while (pageToken != null);

    return result;
  }

  private static void printFile(final Drive service, final String fileId) {
    try {
      File file = service.files().get(fileId).execute();

      System.out.println("File: " + file);

      System.out.println("Title: " + file.getName());
      System.out.println("Description: " + file.getDescription());
      System.out.println("MIME type: " + file.getMimeType());
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
    }
  }

  public static Drive getDriveService() throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    GoogleCredential credential = getCredential();

    final Drive.Builder builder = new Drive.Builder(httpTransport, jsonFactory, credential);
    return builder.setApplicationName("ImageIntegration").build();
  }

  public static void main(String[] args) throws IOException {
    Drive service = getDriveService();
    List<File> files = retrieveAllFiles(service);
    files.forEach(f -> printFile(service, f.getId()));
  }

这些是收到的文件信息:

文件:

{"id":"0B04nobSi7Vhgc3RhcnRlcl9maWxl","kind":"drive#file","mimeType":"application/pdf","name":"Getting started"}
Disconnected from the target VM, address: '127.0.0.1:50725', transport: 'socket'
Title: Getting started
Description: null
MIME type: application/pdf

0 个答案:

没有答案