You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google Drive API Java版移文件至回收站时遇403错误求助

问题:Google Drive API 403错误(字段不可写)

尝试用Java版Google Drive API将文件移至回收站,执行以下Kotlin代码时触发403 Forbidden错误:

val file = service.files().get(fileId).execute()
file.setTrashed(true)
service.files().update(fileId, file).execute()

错误信息:

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
POST https://www.googleapis.com/drive/v3/files/0B0XJAu1tqe0ZT01ZSzRLb3Zfa3c
{
  "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."
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:118)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:37)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:439)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1111)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:525)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:466)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:576)
    at DriveQuickstart.main(DriveQuickstart.kt:97)

错误原因

Drive API v3中,files().get(fileId).execute()返回的File对象包含大量只读字段(如创建时间、文件大小、所有者信息等)。直接将这个完整对象传入update方法时,API会尝试处理所有字段,而只读字段不允许被修改,因此触发403错误。

解决方法

不需要获取完整的File对象,只需创建一个仅包含trashed字段的最小化File对象,再调用update接口即可。这样只会提交可写的字段,避免触发只读字段的校验。

修正后的代码:

val file = File().setTrashed(true)
service.files().update(fileId, file).execute()

也可以在update时指定只更新trashed字段(可选优化):

val file = File().setTrashed(true)
service.files().update(fileId, file).setFields("trashed").execute()

内容的提问来源于stack exchange,提问作者xeno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:33:10