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

时间:2015-10-21 04:25:33

标签: java google-drive-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;
    }
}

当我运行该功能时,它会成功构建。但我没有看到任何东西,这样的下载文件等等。

1 个答案:

答案 0 :(得分:0)

这是我在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;
  }

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

祝你好运

相关问题