使用 Google 的 Google Drive SDK (v2-rev57-1.13.2-beta),我尝试导出 Google 的专有格式。我能够很好地下载非专有格式。
要获取文件的路径,documentation说要打电话:
com.google.api.services.drive.model.File.getExportLinks("application/vnd.openxmlformats-officedocument.wordprocessingml.document")
将(例如)Google 文档导出为 MS Word 文档。这样做会产生一个明显有效的 URL。 (我也用“text/plain”尝试过,结果相同)。
但是,当我尝试从该路径下载时,Google Drive SDK 在内部抛出 NullPointerException:
java.lang.NullPointerException
at com.google.api.client.googleapis.media.MediaHttpDownloader.download(MediaHttpDownloader.java:194)
at com.google.api.client.googleapis.media.MediaHttpDownloader.download(MediaHttpDownloader.java:150)
at com.redacted.mycode.GoogleDocsConnection.download(GoogleDocsConnection.java:182)
...
还有其他人遇到过这种情况吗?我正在考虑自己修改 Google 的 SDK,但我想看看是否有人已经遇到过这个问题(也许找到了解决方案)。
谢谢
最佳答案
更新答案:
我没有仔细阅读最初的问题,也没有注意到这种情况只发生在 Google 原生格式的文档中。
获得文档的有效导出链接后,您必须构建授权的 GET 请求。执行此操作的代码与下面 files.get
代码段中的代码类似,您只需将下载 url 替换为导出 url:
private static InputStream downloadFile(Drive service, String exportUrl) {
try {
HttpResponse resp =
service.getRequestFactory()
.buildGetRequest(new GenericUrl(exportUrl))
.execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
}
旧答案(请忽略):
NullPointer 异常可能是由未经授权的初始下载请求引起的。以下代码演示了如何从云端硬盘下载文件:
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;
}
}
只需确保您传递给 downloadFile
的 service
实例已正确授权。
如果您使用此代码并且确定您的服务已正确授权,请显示您的应用发送的 HTTP 请求以及相应的响应。
关于java - NullPointer 尝试导出 Google 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15079663/