Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Mỗi tài nguyên đều có một trường phiên bản thay đổi mỗi khi tài nguyên thay đổi – trường etag. Etag là một phần tiêu chuẩn của HTTP và được hỗ trợ trong API Lịch cho 2 trường hợp:
đối với các nội dung sửa đổi tài nguyên để đảm bảo rằng không có hoạt động ghi nào khác vào tài nguyên này trong thời gian chờ (sửa đổi có điều kiện)
khi truy xuất tài nguyên để chỉ truy xuất dữ liệu tài nguyên nếu tài nguyên đã thay đổi (truy xuất có điều kiện)
Sửa đổi có điều kiện
Nếu chỉ muốn cập nhật hoặc xoá một tài nguyên nếu tài nguyên đó không thay đổi kể từ lần gần nhất bạn truy xuất, bạn có thể chỉ định một tiêu đề If-Match chứa giá trị của etag từ lần truy xuất trước. Điều này rất hữu ích để ngăn chặn việc mất các nội dung sửa đổi trên tài nguyên. Các ứng dụng có thể truy xuất lại tài nguyên và áp dụng lại các thay đổi.
Nếu mục nhập (và etag của mục nhập đó) không thay đổi kể từ lần truy xuất gần đây nhất, thì quá trình sửa đổi sẽ thành công và phiên bản mới của tài nguyên có etag mới sẽ được trả về. Nếu không, bạn sẽ nhận được mã phản hồi 412 (Điều kiện tiên quyết không đáp ứng).
Đoạn mã mẫu dưới đây minh hoạ cách thực hiện các hoạt động sửa đổi có điều kiện bằng thư viện ứng dụng Java.
privatestaticvoidrun()throwsIOException{// Create a test event.Eventevent=Utils.createTestEvent(client,"Test Event");System.out.println(String.format("Event created: %s",event.getHtmlLink()));// Pause while the user modifies the event in the Calendar UI.System.out.println("Modify the event's description and hit enter to continue.");System.in.read();// Modify the local copy of the event.event.setSummary("Updated Test Event");// Update the event, making sure that we don't overwrite other changes.intnumAttempts=0;booleanisUpdated=false;do{Calendar.Events.Updaterequest=client.events().update("primary",event.getId(),event);request.setRequestHeaders(newHttpHeaders().setIfMatch(event.getEtag()));try{event=request.execute();isUpdated=true;}catch(GoogleJsonResponseExceptione){if(e.getStatusCode()==412){// A 412 status code, "Precondition failed", indicates that the etag values didn't// match, and the event was updated on the server since we last retrieved it. Use// {@link Calendar.Events.Get} to retrieve the latest version.EventlatestEvent=client.events().get("primary",event.getId()).execute();// You may want to have more complex logic here to resolve conflicts. In this sample we're// simply overwriting the summary.latestEvent.setSummary(event.getSummary());event=latestEvent;}else{throwe;}}numAttempts++;}while(!isUpdated && numAttempts<=MAX_UPDATE_ATTEMPTS);if(isUpdated){System.out.println("Event updated.");}else{System.out.println(String.format("Failed to update event after %d attempts.",numAttempts));}}
Nếu chỉ muốn truy xuất một tài nguyên nếu tài nguyên đó đã thay đổi kể từ lần truy xuất gần đây nhất, bạn có thể chỉ định một tiêu đề If-None-Match chứa giá trị của etag từ lần truy xuất trước đó. Nếu mục nhập (và do đó là etag của mục nhập) đã thay đổi kể từ lần truy xuất gần đây nhất, thì phiên bản mới của tài nguyên có etag mới sẽ được trả về. Nếu không, bạn sẽ nhận được mã phản hồi 304 (Chưa được sửa đổi).
Đoạn mã mẫu dưới đây minh hoạ cách thực hiện truy xuất có điều kiện bằng thư viện ứng dụng Java.
privatestaticvoidrun()throwsIOException{// Create a test event.Eventevent=Utils.createTestEvent(client,"Test Event");System.out.println(String.format("Event created: %s",event.getHtmlLink()));// Pause while the user modifies the event in the Calendar UI.System.out.println("Modify the event's description and hit enter to continue.");System.in.read();// Fetch the event again if it's been modified.Calendar.Events.GetgetRequest=client.events().get("primary",event.getId());getRequest.setRequestHeaders(newHttpHeaders().setIfNoneMatch(event.getEtag()));try{event=getRequest.execute();System.out.println("The event was modified, retrieved latest version.");}catch(GoogleJsonResponseExceptione){if(e.getStatusCode()==304){// A 304 status code, "Not modified", indicates that the etags match, and the event has// not been modified since we last retrieved it.System.out.println("The event was not modified, using local version.");}else{throwe;}}}
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2025-08-29 UTC."],[],[],null,["# Get specific versions of resources\n\nEvery resource has a version field that changes every time the resource\nchanges --- the `etag` field. Etags are a standard part of HTTP and are\nsupported in the calendar API for two cases:\n\n- on resource modifications to ensure that there has been no other write to this resource in the meantime (conditional modification)\n- on resource retrieval to only retrieve resource data if the resource has changed (conditional retrieval)\n\nConditional modification\n------------------------\n\nIf you want to update or delete a resource only if it has not changed since\nyou last retrieved it, you can specify an `If-Match` header that contains the\nvalue of the etag from the previous retrieval. This is very useful to prevent\nlost modifications on resources. The clients have the option of re-retrieving\nthe resource and re-applying the changes.\n\nIf the entry (and its etag) has not changed since the last retrieval, the\nmodification succeeds and the new version of the resource with the new etag is\nreturned. Otherwise, you will get a 412 (Precondition failed) response code.\n| **Important:** There is no support for conditional modifications for insert operations. Instead, it is guaranteed that if you are allowed to provide a resource ID, then the operation will only succeed if no existing entry has that ID.\n\nThe snippet of sample code below demonstrates how to perform conditional\nmodifications with the\n[Java client library](/api-client-library/java/apis/calendar/v3). \n\n```java\n private static void run() throws IOException {\n // Create a test event.\n Event event = Utils.createTestEvent(client, \"Test Event\");\n System.out.println(String.format(\"Event created: %s\", event.getHtmlLink()));\n\n // Pause while the user modifies the event in the Calendar UI.\n System.out.println(\"Modify the event's description and hit enter to continue.\");\n System.in.read();\n\n // Modify the local copy of the event.\n event.setSummary(\"Updated Test Event\");\n\n // Update the event, making sure that we don't overwrite other changes.\n int numAttempts = 0;\n boolean isUpdated = false;\n do {\n Calendar.Events.Update request = client.events().update(\"primary\", event.getId(), event);\n request.setRequestHeaders(new HttpHeaders().setIfMatch(event.getEtag()));\n try {\n event = request.execute();\n isUpdated = true;\n } catch (GoogleJsonResponseException e) {\n if (e.getStatusCode() == 412) {\n // A 412 status code, \"Precondition failed\", indicates that the etag values didn't\n // match, and the event was updated on the server since we last retrieved it. Use\n // {@link Calendar.Events.Get} to retrieve the latest version.\n Event latestEvent = client.events().get(\"primary\", event.getId()).execute();\n\n // You may want to have more complex logic here to resolve conflicts. In this sample we're\n // simply overwriting the summary.\n latestEvent.setSummary(event.getSummary());\n event = latestEvent;\n } else {\n throw e;\n }\n }\n numAttempts++;\n } while (!isUpdated && numAttempts \u003c= MAX_UPDATE_ATTEMPTS);\n\n if (isUpdated) {\n System.out.println(\"Event updated.\");\n } else {\n System.out.println(String.format(\"Failed to update event after %d attempts.\", numAttempts));\n }\n }https://github.com/googleworkspace/java-samples/blob/26cb124371d51cb5cb8e6c4a3db6422bbef586fb/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/ConditionalModificationSample.java\n```\n\nConditional retrieval\n---------------------\n\nIf you want to retrieve a resource only if it has changed since you last\nretrieved it, you can specify an `If-None-Match` header which contains the\nvalue of the etag from the previous retrieval. If the entry (and thus its etag)\nhas changed since the last retrieval, the new version of the resource with the\nnew etag will be returned. Otherwise you will get a 304 (Not Modified)\nresponse code.\n| **Note:** There are special cases in which etags won't change, such as when one of the read-only fields of a `calendarList` entry changes (e.g., calendar properties or ACLs).\n\nThe snippet of sample code below demonstrates how to perform conditional\nretrieval with the\n[Java client library](/api-client-library/java/apis/calendar/v3). \n\n```java\n private static void run() throws IOException {\n // Create a test event.\n Event event = Utils.createTestEvent(client, \"Test Event\");\n System.out.println(String.format(\"Event created: %s\", event.getHtmlLink()));\n\n // Pause while the user modifies the event in the Calendar UI.\n System.out.println(\"Modify the event's description and hit enter to continue.\");\n System.in.read();\n\n // Fetch the event again if it's been modified.\n Calendar.Events.Get getRequest = client.events().get(\"primary\", event.getId());\n getRequest.setRequestHeaders(new HttpHeaders().setIfNoneMatch(event.getEtag()));\n try {\n event = getRequest.execute();\n System.out.println(\"The event was modified, retrieved latest version.\");\n } catch (GoogleJsonResponseException e) {\n if (e.getStatusCode() == 304) {\n // A 304 status code, \"Not modified\", indicates that the etags match, and the event has\n // not been modified since we last retrieved it.\n System.out.println(\"The event was not modified, using local version.\");\n } else {\n throw e;\n }\n }\n }https://github.com/googleworkspace/java-samples/blob/26cb124371d51cb5cb8e6c4a3db6422bbef586fb/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/ConditionalRetrievalSample.java\n```"]]