发送批量请求

应用建立的每个 HTTP 连接都会产生一定的开销。此库支持批处理,可让您的应用将多个 API 调用放入单个 HTTP 请求中。以下是您可能需要使用批处理的情形示例:

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

注意:一个批量请求最多只能包含 1,000 个调用。 如果您需要进行更多调用,请使用多个批量请求。

注意:不能在批量请求中使用媒体上传对象。

具体说明

如需创建批量请求,请实例化 BatchRequest 对象,然后针对要执行的每个请求调用 Queue 方法。对每个请求传入回调,以便在应用收到对该请求的响应时调用。 回调函数的参数如下:

content
内容响应,如果请求失败,则为 null
error
错误,如果请求成功,则返回 null
index
单个请求的索引。
信息
包含其所有标头和内容的完整 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();