Please can someone provide example code in C# that will allow me to submit a batch request to the Google Indexing API for the URL_UPDATED action? The code below shows what I currently use to perform a single URL_UPDATED action using a single HTTP Request.
Ideally, I would like to supply a string[] of Urls that can be passed to the batch function.
Thanks.
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;
}
}
}