Google Drive API:使用Java下载文件

Google Drive API:使用Java下载文件

问题描述:

因此,使用Google Drive的API,我试图从我的驱动器帐户下载文件。我遵循Google的快速入门指南(https://developers.google.com/drive/web/quickstart/java),并使用Google的DriveQuickStart.java初始化Drive对象。Google Drive API:使用Java下载文件

对象的一切正常工作(即从我的谷歌驱动器帐户获取所有文件并显示其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); 

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