你是对的,谷歌的文档要么不存在,要么很糟糕。甚至他们自己的文档中也有损坏或未完成的页面,在其中一个文档中,您会被指向一个不存在的 nuget 包。通过将 SA 上的其他 Auth 示例组合在一起,然后遵循 Java 索引文档,可以使其工作。
首先,您需要使用 nuget 包管理器添加主 api 包和 auth 包:
然后尝试以下操作:
using System;
using System.Configuration;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Http;
using Newtonsoft.Json;
namespace MyProject.Common.GoogleForJobs
{
public class GoogleJobsClient
{
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");
}
private static GoogleCredential GetGoogleCredential()
{
var path = ConfigurationManager.AppSettings["GoogleForJobsJsonFile"];
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;
}
private async Task<HttpResponseMessage> PostJobToGoogle(string jobUrl, string action)
{
var googleCredential = GetGoogleCredential();
var serviceAccountCredential = (ServiceAccountCredential) googleCredential.UnderlyingCredential;
const 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;
}
}
}
然后你可以这样称呼它
var googleJobsClient = new GoogleJobsClient();
var result = await googleJobsClient.AddOrUpdateJob(url_of_vacancy);
或者,如果您不在异步方法中
var googleJobsClient = new GoogleJobsClient();
var result = googleJobsClient.AddOrUpdateJob(url_of_vacancy).Result;