java - 谷歌驱动器 API : Downloading a file in Java

标签 java google-drive-api

因此,我尝试使用 Google Drive 的 API 从我的云端硬盘帐户下载一个文件。我遵循了 Google 的快速入门指南 (https://developers.google.com/drive/web/quickstart/java) 并使用了 Google 的 DriveQuickStart.java 来初始化 Drive 对象。

对象的一切都正常工作(即从我的谷歌驱动器帐户获取所有文件并显示它们的 ID 和标题);但是,当我尝试通过 Google 开发的函数的输入流下载文件时,我不断收到空异常错误。

这是我使用的代码:

 private static InputStream downloadFile(Drive service, File file) {
        if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
            try {
                HttpResponse resp =
                        service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
                                .execute();
                return resp.getContent();
            } catch (IOException e) {
                // An error occurred.
                e.printStackTrace();
                return null;
            }
        } else {
            // The file doesn't have any content stored on Drive.
            return null;
        }
    }

问题是当方法调用 file.getDownloadURL() 时,它返回一个空值。根据文档,如果我尝试下载的文件是原生的 Google Drive 文件,它应该返回一个空值;但是,我正在下载的文件只是一个 jar 文件,所以不可能是因为文件扩展名(我也尝试过其他格式)。

为什么它返回一个空值,我该怎么做才能解决这个问题?谢谢!

最佳答案

想通了。

对于遇到过这个问题的其他人来说,答案非常简单: 在DriveQuickStart.java代码中,注意这部分:

    /** Global instance of the scopes required by this quickstart. */
private static final List<String> SCOPES =
    Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);

并确保将其设置为:

    /** Global instance of the scopes required by this quickstart. */
private static final List<String> SCOPES =
    Arrays.asList(DriveScopes.DRIVE);

所以它不起作用的唯一原因是因为程序没有适当的权限来这样做。

关于java - 谷歌驱动器 API : Downloading a file in Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31374233/

相关文章:

java - X 天后从数据库中删除项目

java - 在新的 Eclipse 安装中重新索引本地 Maven Repo 失败并出现 java.nio.channels.OverlappingFileLockException

google-apps-script - 使用Google Script的Web App作为Webhook直接接收推送通知

java - 基于给定权重 vector 的随机选择问题

java - 检测流是否用 Java 压缩的最佳方法

java - 使用升序和降序数字在 Java 中打印居中金字塔

c# - 如何上传 Excel 文件并以编程方式将其转换为 Google 电子表格?

java - Eclipse IDE 无法与 Google 备份和同步一起使用

php - 使用 PHP 将文件备份到谷歌驱动器

google-drive-api - 如何在多个帐户上获取 Google Drive 应用程序