请有人提供 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;
}
}
}