java google 驱动器 API 无法下载二进制文件

java google drive API unable to download binary file

我有工作代码来列出我的 Google 驱动器文件夹中包含二进制文件的文件,但我在尝试下载时遇到错误:

GET https://www.googleapis.com/download/drive/v3/files/1udFizffA_0M4jSUBJbDI6uNVdPVhdymW?alt=media
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "location" : "alt",
    "locationType" : "parameter",
    "message" : "Only files with binary content can be downloaded. Use Export with Docs Editors files.",
    "reason" : "fileNotDownloadable"
  } ],
  "message" : "Only files with binary content can be downloaded. Use Export with Docs Editors files."
}

相关代码如下:

Drive.Files f = driveService.files();
HttpResponse httpResponse = null;
Drive.Files.Get get = f.get(file.getId());
httpResponse = get.executeMedia();

我也试过导出使用:

httpResponse = f.export(file.getId(),"application/octet-stream").executeMedia();

也没用。

谁能帮我弄清楚我错过了什么。

file.get 方法会 return 文件数据,但仅适用于二进制文件类型。这就是此错误消息告诉您的内容。

Only files with binary content can be downloaded. Use Export with Docs Editors files.

String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
    .executeMediaAndDownloadTo(outputStream);

所有其他文件类型是 google 文档,google 表格。查看此页面了解更多信息:mimetype

需要从 google mime 类型导出为标准 mime 类型。如果您查看 manage-downloads#java 页面,您会找到有关如何使用此方法的文档示例。

String fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().export(fileId, "application/pdf")
    .executeMediaAndDownloadTo(outputStream);

此方法的诀窍是确保您设置正确 mimetype