发送批量请求

应用建立的每个 HTTP 连接都会产生一定的开销。 此库支持批处理 以允许您的应用将多个 API 调用组合为一个 HTTP 请求。 在以下示例情况下,您可能需要使用批处理:

  • 您要发出许多小请求,并且希望最大程度地减少 HTTP 请求开销。
  • 用户在您的应用处于离线状态时对数据进行了更改, 因此您的应用需要将其本地数据与服务器同步 发送大量更新和删除信息。

注意:单个批量请求最多只能调用 1,000 次调用。 如果您需要发出更多调用,请使用多个批量请求。

注意:您不能使用 媒体上传 对象。

详细信息

您可以通过将 BatchRequest 对象,然后为要执行的每个请求调用 Queue 方法。 对于每个请求,请传入一个回调,该回调将在应用收到 对该请求的响应 回调函数的实参如下:

内容
内容响应,如果请求失败,则为 null
错误
错误,如果请求成功,则为 null
索引
单个请求的索引。
消息
包含其所有标头和内容的完整 HTTP 消息。
添加请求后,调用 ExecuteAsync 方法发出请求。

在以下代码段中, 系统会将两个 API 请求批量处理为一个 HTTP 请求 并且每个 API 请求都会获得一个回调:

UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        new[] { CalendarService.Scope.Calendar },
        "user", CancellationToken.None, new FileDataStore("Calendar.Sample.Store"));
}

// Create the service.
var service = new CalendarService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "Google Calendar API Sample",
    });

// Create a batch request.
var request = new BatchRequest(service);
request.Queue<CalendarList>(service.CalendarList.List(),
     (content, error, i, message) =>
     {
         // Put your callback code here.
     });
request.Queue<Event>(service.Events.Insert(
     new Event
     {
         Summary = "Learn how to execute a batch request",
         Start = new EventDateTime() { DateTime = new DateTime(2014, 1, 1, 10, 0, 0) },
         End = new EventDateTime() { DateTime = new DateTime(2014, 1, 1, 12, 0, 0) }
     }, "YOUR_CALENDAR_ID_HERE"),
     (content, error, i, message) =>
     {
         // Put your callback code here.
     });
// You can add more Queue calls here.

// Execute the batch request, which includes the 2 requests above.
await request.ExecuteAsync();