gpt4 book ai didi

java - (Java) 下载 URL 不起作用

转载 作者:行者123 更新时间:2023-12-01 09:27:52 24 4
gpt4 key购买 nike

我正在努力尝试使用 Google Drive API 下载文件。我只是编写代码,将文件从我的驱动器下载到我的计算机上。我终于到达了通过身份验证并可以查看文件元数据的阶段。由于某种原因,我仍然无法下载文件。我得到的 downLoadURL 看起来像:

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

当我运行代码或将其复制并粘贴到浏览器中时,此 URl 不会下载任何内容。但是,在浏览器中,当我删除 URL 的“&gd=true”部分时,它会下载文件。

我的下载方法直接来自Google Drive 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;
}
}

有人知道这是怎么回事吗?

提前致谢。

最佳答案

由于您使用的是 Drive v2,因此您可以采用不同的方法(也在 the documentation 上)通过 HttpRequest 对象获取 InputStream

/**
* 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 - (Java) 下载 URL 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39693252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com