Google Drive API v3迁移

时间:2016-02-02 01:00:08

标签: google-drive-api

我决定从Google Drive API v2迁移到v3,这不是一件容易的事。即使谷歌写这篇文章documentation,也有很多空白,网上没有太多关于此的信息。

我在这里分享我找到的东西。

2 个答案:

答案 0 :(得分:38)

首先,阅读官方文档:Migrate to Google Drive API v3

下载

Download已发生变化。字段downloadUrl不再存在。现在,它可以实现:

service.files().get(fileId).executeMediaAndDownloadTo(outputStream);

我尝试了新字段webContentLink,但它返回HTML内容,而不是文件的内容。换句话说,它为您提供了Drive Web UI的链接。

上传

仅上传需要更改insert的单词create,仅此而已。

废纸篓/更新

我浪费了一些时间。曾经是一个简单的service.files().trash(fileId).execute()。 文件说

  

files.trash - > files.update with {' trashed':true}

v2上update的{​​{3}}在文件上生成get,设置新值,然后调用update

在v3上,使用类似update会抛出此异常:

{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "The resource body includes fields which are not directly writable.",
    "reason" : "fieldNotWritable"
  } ],
  "message" : "The resource body includes fields which are not directly writable."
}

解决方案是仅创建一个空的File设置新值:

File newContent = new File();
newContent.setTrashed(true);
service.files().update(fileId, newContent).execute();

注意:File是指com.google.api.services.drive.model.File(不是java.io.File)。

列表

service.files().list()返回的文件现在不包含信息,即每个字段都为空。如果您希望v3上的list与v2中的行为相同,请按以下方式调用它:

service.files().list().setFields("nextPageToken, files");

example code上的文档使用setFields("nextPageToken, files(id, name)"),但没有关于如何获取文件的所有信息的文档。现在你知道了,只需要包含"文件"。

字段

  

默认情况下不再返回完整资源。使用fields查询参数请求返回特定字段。如果未指定,则仅返回常用字段的子集。

最后一部分并非完全正确,因为在某些情况下你被迫使用setFields。例如,如果您使用service.about().get().execute(),则会收到此错误:

"The 'fields' parameter is required for this method."

例如,通过调用service.about().get().setFields("user, storageQuota").execute()来解决。

在文档的最后提到:

  

应为返回

的方法指定fields查询参数

对于其他更改,只需按照文档上的Google表格进行操作。

答案 1 :(得分:0)

我没有评论的能力(抱歉),但是接受的答案service.about().get().setFields("user, storageQuota").execute()中提供的代码行未运行,而是引发了属性错误:

    about = service.about().get().setFields("user", "storageQuota").execute()
AttributeError: 'HttpRequest' object has no attribute 'setFields'

相反,该行应显示为:

service.about().get(fields = "user, storageQuota").execute()
相关问题