【问题标题】:(Java) Download URL not working(Java) 下载 URL 不起作用
【发布时间】:2016-09-26 00:43:44
【问题描述】:

我正在努力尝试使用 google drive API 下载文件。我只是在编写代码,应该将文件从我的驱动器下载到我的计算机上。我终于到了经过身份验证并可以查看文件元数据的阶段。由于某种原因,我仍然无法下载文件。我得到的 downLoadURL 看起来像:

https://doc-04-as-docs.googleusercontent.com/docs/securesc/XXXXXXXXXXXXXX/0B4dSSlLzQCbOXzAxNGxuRUhVNEE?e=download&gd=true

当我运行我的代码或将其复制并粘贴到浏览器中时,此 URl 没有下载任何内容。但是,在浏览器中,当我删除 URL 的“&gd=true”部分时,它会下载文件。

我的下载方法直接来自google drive API文档:

public static InputStream downloadFile(Drive service, File file) {
  if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
    try {
      System.out.println("Downloading: "+ file.getTitle());
      return service.files().get(file.getId()).executeMediaAsInputStream();
    } catch (IOException e) {
      // An error occurred.
      e.printStackTrace();
      return null;
    }
  } else {
    // The file doesn't have any content stored on Drive.
    return null;
  }
}

有人知道这里发生了什么吗?

提前致谢。

【问题讨论】:

    标签: java google-app-engine oauth-2.0 google-drive-api


    【解决方案1】:

    由于您使用的是 Drive v2,另一种方法(也在 the documentation 上)是让您通过 HttpRequest 对象获取 InputStream

    /**
    * Download a file's content.
    *
    * @param service Drive API service instance.
    * @param file Drive File instance.
    * @return InputStream containing the file's content if successful,
    * {@code null} otherwise.
    */
    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-02
      • 1970-01-01
      • 2021-10-23
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 2017-09-20
      相关资源
      最近更新 更多