繁体   English   中英

无法使用Java API从Google云端硬盘下载文件

[英]Unable to download file from Google Drive using Java API

我已经尝试了Google驱动器的某些功能,但是无法从驱动器下载文件。 我是否缺少创建文件的功能?

private static InputStream downloadFile(Drive authKey, File file) {
    if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
        try {
            HttpResponse resp
                    = authKey.getRequestFactory().buildGetRequest(new GenericUrl(
                                    file.getDownloadUrl())).execute();
            //System.out.println("File Successfully Downloaded");
            return resp.getContent();
        } catch (IOException e) {
            // An error occurred.
            e.printStackTrace();
            //System.out.println("Failed to Download File");
            return null;
        }
    } else {
        return null;
    }
}

当我运行该功能时,它会成功构建。 但我什么也没看到,例如下载的文件等。

这是我在Android上使用的构造,无论如何您都可以尝试一下。

  private static InputStream downloadFile(Drive authKey, File file) {
      if (authKey != null && file != null) try {
        File gFl = authKey.files().get(file.getId()).setFields("downloadUrl").execute();
        if (gFl != null){
          return authKey.getRequestFactory()
            .buildGetRequest(new GenericUrl(gFl.getDownloadUrl()))
            .execute().getContent();
        }
      } catch (Exception e) { e.printStackTrace(); }
      return null;
  }

(但效率低下,往返2次)

更新
我花了一些时间通过我的Android调试/测试应用程序运行了您的代码,可以确认它失败了。

  private static InputStream downloadFile(Drive authKey, File file) {
//    if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) try {
//      return authKey.getRequestFactory()
//        .buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute().getContent();
//    } catch (IOException e) { e.printStackTrace();  }
//    return null;

    if (authKey != null && file != null) try {
      File gFl = authKey.files().get(file.getId()).setFields("downloadUrl").execute();
      if (gFl != null){
        return mGOOSvc.getRequestFactory()
          .buildGetRequest(new GenericUrl(gFl.getDownloadUrl()))
          .execute().getContent();
      }
    } catch (Exception e) { e.printStackTrace(); }
    return null;
  }

上面代码的注释掉部分是失败的品种。

祝好运

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM