(Java) Download URL not working

2019-06-10 04:01发布

I am battling with trying to download files using the google drive API. I'm just writing code that should download files from my drive onto my computer. I've finally got to a stage where I am authenticated and can view the file metadata. For some reason, I'm still unable to download files. The downLoadURL I get looks like:

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

This URl isn't downloading anything when I run my code or when I copy and paste it in a browser. But, in the browser, when i remove the "&gd=true" part of the URL it downloads the file.

My download method is straight out of the google drive API documentation:

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

Anyone know whats going on here?

Thanks in advance.

1条回答
趁早两清
2楼-- · 2019-06-10 04:23

Since you're using Drive v2, a different approach (also on the documentation) is for you to get the InputStream thru the HttpRequest object.

/**
* 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;
    }
}
查看更多
登录 后发表回答