1

请有人提供 C# 中的示例代码,允许我向 Google Indexing API 提交批量请求以执行 URL_UPDATED 操作?下面的代码显示了我当前使用单个 HTTP 请求执行单个 URL_UPDATED 操作的方法。

理想情况下,我想提供一个可以传递给批处理函数的 URL 字符串 []。

谢谢。

using Google.Apis.Auth.OAuth2;
using Google.Apis.Http;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace GoogleServiceAccounts
{
  public class Indexing
  {
    public GoogleServiceAccount _googleServiceAccount;
    private IConfigHelper _configHelper;
    private GoogleCredential _googleCredential;
    private IHostingEnvironment _hostingEnvironment;

    public Indexing(IConfigHelper configHelper, IHostingEnvironment hostingEnvironment)
    {
      _configHelper = configHelper;
      _hostingEnvironment = hostingEnvironment;
      _googleServiceAccount = _configHelper.Settings.GoogleServiceAccounts.SingleOrDefault(a => a.Name == "Indexing");
      _googleCredential = GetGoogleCredential();
    }

    public async Task<HttpResponseMessage> AddOrUpdateJob(string jobUrl)
    {
      return await PostJobToGoogle(jobUrl, "URL_UPDATED");
    }

    public async Task<HttpResponseMessage> CloseJob(string jobUrl)
    {
      return await PostJobToGoogle(jobUrl, "URL_DELETED");
    }

    public async Task<HttpResponseMessage> PostJobToGoogle(string jobUrl, string action)
    {
      var serviceAccountCredential = (ServiceAccountCredential)_googleCredential.UnderlyingCredential;

      string googleApiUrl = "https://indexing.googleapis.com/v3/urlNotifications:publish";

      var requestBody = new
      {
        url = jobUrl,
        type = action
      };

      var httpClientHandler = new HttpClientHandler();

      var configurableMessageHandler = new ConfigurableMessageHandler(httpClientHandler);

      var configurableHttpClient = new ConfigurableHttpClient(configurableMessageHandler);

      serviceAccountCredential.Initialize(configurableHttpClient);

      HttpContent content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");

      var response = await configurableHttpClient.PostAsync(new Uri(googleApiUrl), content);

      return response;
    }

    private GoogleCredential GetGoogleCredential()
    {
      var path = _hostingEnvironment.MapPath(_googleServiceAccount.KeyFile);
      GoogleCredential credential;

      using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
      {
        credential = GoogleCredential.FromStream(stream).CreateScoped(new[] { "https://www.googleapis.com/auth/indexing" });
      }

      return credential;
    }
  }
}
4

1 回答 1

0

我已经扩展了您的示例,这是发出批处理请求的代码。

private async Task<List<PublishUrlNotificationResponse>> BatchAddUpdateIndex(IEnumerable<string> jobUrls, string action)
{
        var credential = _googleCredential.UnderlyingCredential;

        var googleIndexingApiClientService = new IndexingService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new BatchRequest(googleIndexingApiClientService);

        var notificationResponses = new List<PublishUrlNotificationResponse>();

        foreach (var url in jobUrls)
        {
            var urlNotification = new UrlNotification
            {
                Url = url,
                Type = action
            };

            request.Queue<PublishUrlNotificationResponse>(
                new UrlNotificationsResource.PublishRequest(googleIndexingApiClientService, urlNotification), (response, error, i, message) =>
                {
                    notificationResponses.Add(response);
                });
        }

        await request.ExecuteAsync();

        return await Task.FromResult(notificationResponses);
}

这是一个以批处理方式获取 URL 状态的示例。

private async Task<List<UrlNotificationMetadata>> BatchGetIndexStatus(IEnumerable<string> jobUrls)
{
        var credential = _googleCredential.UnderlyingCredential;

        var googleIndexingApiClientService = new IndexingService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new BatchRequest(googleIndexingApiClientService);

        var metaDataResponses = new List<UrlNotificationMetadata>();

        foreach (var url in jobUrls)
        {
            request.Queue<UrlNotificationMetadata>(
                new GetMetadataRequest(googleIndexingApiClientService, url), (response, error, i, message) =>
                {
                    metaDataResponses.Add(response);
                });
        }

        await request.ExecuteAsync();

        return await Task.FromResult(metaDataResponses);
}

你也可以看看我的博客文章,还有一个示例存储库,你可以在我的博客文章的末尾找到。

于 2019-12-08T00:21:29.697 回答