(Java)下载网址无法正常工作
问题描述:
我正在努力尝试使用谷歌驱动器API下载文件。我只是写代码,应该从我的驱动器下载文件到我的电脑上。我终于进入了一个认证阶段,可以查看文件元数据。出于某种原因,我仍然无法下载文件。我得到的将downloadURL样子:(Java)下载网址无法正常工作
此网址不能下载任何东西,当我运行我的代码或当我复制并粘贴在浏览器中。但是,在浏览器中,当我删除其下载该文件的URL的“& gd = true”部分时。
我下载的方法是直接从谷歌驱动API文档:
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;
}
}
任何人都知道什么是怎么回事呢?
在此先感谢。
答
由于您使用的驱动器V2,采用不同的方法(也the documentation)是您获得InputStream
通的HttpRequest
对象。
/**
* 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;
}
}