(Java)下载网址无效 [英] (Java) Download URL not working
问题描述
我正在努力尝试使用谷歌驱动器API下载文件。我只是写代码,应该从我的驱动器下载文件到我的电脑上。我终于进入了一个认证阶段,可以查看文件元数据。出于某种原因,我仍然无法下载文件。我收到的downLoadURL如下所示:
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:
当我运行我的代码或将其复制并粘贴到浏览器中时,URl不会下载任何内容。但是,在浏览器中,当我删除URL的& 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.
我的下载方法是直接从Google驱动器API文档:
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?
在此先感谢。
推荐答案
由于您使用Drive v2,方法(同样在文档上)是为了获得 InputStream
通过 HttpRequest
对象。
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;
}
}
这篇关于(Java)下载网址无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!