Detect conflict when uploading document to Google Drive

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 07:47:55

"Is this the correct way to use ETag?"

Yes

Also, for non-Docs files, you should also check md5Checksum for changes to the content.

Juuso Ohtonen

Set the If-Match HTTP header:

final Update update = mService.files().update(mDriveFile.getId(), mDriveFile, byteContent);
final HttpHeaders headers = update.getRequestHeaders();
headers.setIfMatch(mDriveFile.getEtag());
update.setRequestHeaders(headers);
mDriveFile = update.execute();

In case the document has changed meanwhile, the update will get rejected with a response something like:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 412 Precondition Failed
{
  "code": 412,
  "errors": [
    {
      "domain": "global",
      "location": "If-Match",
      "locationType": "header",
      "message": "Precondition Failed",
      "reason": "conditionNotMet"
    }
  ],
  "message": "Precondition Failed"
}

Note that ETag might change even if the content does not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!