简体   繁体   中英

Unable to download file from Google Drive using Java API

I have tried some functions of Google drive, but I couldn't able to download the file from Drive. Am i missing some function to create the file?

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;
    }
}

When i run the function, it build successfully. but i don't see anything, such a downloaded file or etc.

This is the construct I use on Android, you may try to give it a shot anyway.

  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;
  }

(inefficient though, 2 roundtrips)

UPDATE
I took some time and ran your code through my Android debug/test app and can confirm that it failed.

  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;
  }

The commented-out section of the code above is the failing variety.

Good Luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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