简体   繁体   English

Gmail API批量获取邮件的请求返回401(需要登录)

[英]Gmail API Batch Request to get Messages returns 401 (Login Required)

I am attempting to write some code that fetches emails from Gmail using the Gmail API documented here . 我正在尝试编写一些代码,以使用此处记录的Gmail API从Gmail提取电子邮件。 I have successfully managed to retrieve a list of emails, and to get details of individual emails. 我已成功设法检索了电子邮件列表,并获取了各个电子邮件的详细信息。

What I would like to do now is to use a BatchRequest to get details of multiple emails in a single call, but when I try this I get a 401 error with the message: 我现在想做的是使用BatchRequest在单个调用中获取多个电子邮件的详细信息,但是当我尝试执行此操作时,出现以下消息401错误:

Google.Apis.Requests.RequestError Login Required [401] Errors [ Message[Login Required] Location[Authorization - header] Reason[required] Domain[global] ] Google.Apis.Requests.RequestError需要登录[401]错误[消息[需要登录]位置[授权-标头]原因[必需]域[全局]]

In the GetMessageInfo method in the class below, there are three calls to the API: 在下面的类的GetMessageInfo方法中,对API进行了三个调用:

  1. Messages.List This successfully returns a list of messages Messages.List这将成功返回消息列表
  2. Messages.Get This successfully returns details of a single message Messages.Get这将成功返回单个消息的详细信息
  3. Finally, I attempt the same Messages.Get as in Step 2, but this time using a BatchRequest , and this fails with the above error. 最后,我尝试使用与步骤2中相同的Messages.Get ,但是这次使用BatchRequest ,但是由于上述错误而失败。

I am using the same service object each time, and in the case of Steps 2 & 3, I am using the same request. 我每次都使用相同的服务对象,对于步骤2和3,我使用的是相同请求。

QUESTION: Why can I get message details with a single request but not as part of a batch request? 问题:为什么我可以通过单个请求获得消息详细信息,但是不能作为批处理请求的一部分?

public class ProofOfConcept
{
  public void GetMessageInfo()
  {
    GmailService service = GetService();

    UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me");
    request.MaxResults = 1;

    ListMessagesResponse response = request.Execute();
    Message message = response.Messages.First();

    Message fullMessageBySingleRequest = PerformSingleRequest(service, message.Id);
    Message fullMessageByBatchRequest = PerformBatchRequest(service, message.Id, out RequestError error);
  }

  private Message PerformSingleRequest(GmailService service, string messageId)
  {
    UsersResource.MessagesResource.GetRequest request = service.Users.Messages.Get("me", messageId);
    Message message = request.Execute();

    return message;
  }

  private Message PerformBatchRequest(GmailService service, string messageId, out RequestError err)
  {
    UsersResource.MessagesResource.GetRequest messageRequest = service.Users.Messages.Get("me", messageId);

    var batchRequest = new BatchRequest(service);

    Message message = null;
    RequestError requestError = null;

    batchRequest.Queue<Message>(
      messageRequest,
      (content, error, i, msg) =>
      {
        message = content;
        requestError = error;
      });

    batchRequest.ExecuteAsync().Wait();

    err = requestError;
    return message;
  }

  private GmailService GetService()
  {
    UserCredential credential;

    using (var stream = new FileStream(
      @".\ClientSecret\client_secret.json", 
      FileMode.Open, 
      FileAccess.Read))
    {
      string credPath = Environment.GetFolderPath(
        Environment.SpecialFolder.Personal);

      credPath = Path.Combine(
        credPath, 
        ".credentials/gmail-dotnet-quickstart.json");

      credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
          GoogleClientSecrets.Load(stream).Secrets,
          new[] {GmailService.Scope.GmailReadonly},
          "user",
          CancellationToken.None,
          new FileDataStore(credPath, true))
        .Result;
    }

    // Create Gmail API service.
    var service = new GmailService(new BaseClientService.Initializer
    {
      HttpClientInitializer = credential,
      ApplicationName = "Foo"
    });

    return service;
  }
}

OK this got to big for a comment. 好的,这很重要。

For starters I have never bothered with batching on the Google apis. 对于初学者来说,我从来没有为Google api上的批处理而烦恼。 The code linked I have never gotten to work properly ( Imo no fault of the code ), I have tried it with several Google APIs(analytics and drive). 我从未成功链接过的代码链接(我的代码没有错 ),我已经使用多个Google API(分析和驱动器)进行了尝试。 I have never found the Google batching end point to be very stable. 我从未发现Google批处理终点非常稳定。 If one request in the batch request fails or is to slow then they all fail you will get a 500 error back. 如果批处理请求中的一个请求失败或速度变慢,那么所有这些请求都会失败,您将收到500错误的提示。

Second you are not really going to win anything using batching IMO. 其次,使用批处理IMO并不会真正赢得任何收益。 The quota hits will be the same. 配额点击将是相同的。 Sending five requests one at a time and sending one batch with the same five requests is still going to be five against your quota. 一次发送五个请求,并与五个相同的请求发送一批,仍然会超出您的配额(五个)。 Also there is a limit to how many requests you can put in a batch request it depends on the API. 另外,批处理请求中可以放入的请求数也有限制,具体取决于API。 You cant put 100 requests in a batch request i think the limit is more like 10. 您不能在批处理请求中放入100个请求,我认为限制更像是10。

The only thing you may win is the back and forth on the server which if you have a faster internet connection shouldn't really matter. 您可能会赢得的唯一一件事就是在服务器上来回移动,如果您具有较快的Internet连接,则实际上并不重要。

All that being said if you really want to spend the time getting batching working let me know i would be happy to give it a try again. 话虽如此,如果您真的想花时间进行批处理工作,请告诉我,我很乐意再次尝试。 I just think you should consider wither its worth your time or not. 我只是认为您应该考虑是否值得花费其时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM