代码之家  ›  专栏  ›  技术社区  ›  geoff swartz

使用索引API时Google OAuth 2授权

  •  0
  • geoff swartz  · 技术社区  · 7 年前

    我想弄明白 google indexing api 但是他们的文件很糟糕。我已经完成了设置服务帐户和下载JSON文件以及其他先决条件的过程。下一步是获取访问令牌进行身份验证。

    我在一个.NET环境中,但他们没有给出一个例子。我确实找到了一些使用.NET库的例子 here ,但在以下代码之后,我不确定将创建什么服务,然后调用索引API。我在nuget包管理器中没有看到google.apis.indexing库。

    UserCredential credential;
    using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
    {
        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            new[] { "https://www.googleapis.com/auth/indexing" },
            "user", CancellationToken.None, new FileDataStore("IndexingStore"));
    }
    

    在他们的 example code 它看起来像是一个简单的JSON帖子。我试过了,但当然不行,因为我没有被认证。我只是不知道如何在.NET环境中将所有这些联系在一起。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Evolution Rich    7 年前

    你说得对,谷歌的文档要么不存在,要么很糟糕。即使是他们自己的文档中也有破损或未完成的页面,其中一个页面上的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;
    
    推荐文章