对于一家荷兰职业介绍所,我正在尝试编写一些代码,以便在发布或删除新工作时使用 Google 索引 API 更新 google 信息。对于初学者,我尝试获取通知状态,但响应是 404,尽管该网站显然可用。
作为一名初级程序员,我的结论是我可能在某处的代码中犯了错误,或者手头的任务根本不可能,因为我的国家(荷兰)没有正式提供 API
不幸的是,我对位于受支持国家/地区的类似网站没有任何所有权,以确保我的代码是这里的问题。
搜索有关此错误的主题会返回大量信息,但到目前为止,这些信息似乎都不足以解决我的问题。
错误出现在该行using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
下面是我的代码:
using Google.Apis.Auth.OAuth2;
using System.IO;
using System.Threading.Tasks;
class AccessTokenGenerate
{
public static async Task<string> GetAccessTokenFromJSONKeyAsync(string jsonKeyFilePath, params string[] scopes)
{
using (var stream = new FileStream(jsonKeyFilePath, FileMode.Open, FileAccess.Read))
{
return await GoogleCredential
.FromStream(stream) // Loads key file
.CreateScoped(scopes) // Gathers scopes requested
.UnderlyingCredential // Gets the credentials
.GetAccessTokenForRequestAsync(); // Gets the Access Token
}
}
public static string GetAccessTokenFromJSONKey(string jsonKeyFilePath, params string[] scopes)
{
return GetAccessTokenFromJSONKeyAsync(jsonKeyFilePath, scopes).Result;
}
public static async Task<string> GetTokenAndCall()
{
var keyFilePath = @"E:\LocationOnDisk\KeyFilename.json";
var scopes = new[] { "https://www.googleapis.com/auth/indexing" };
GoogleCredential credential;
using (var stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes);
}
var token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
return token;
}
public static string GetToken()
{
var task = GetTokenAndCall();
task.Wait();
var result = task.Result;
return result;
}
}
using System;
using System.IO;
using System.Net;
class Program
{
static void Main(string[] args)
{
var token = AccessTokenGenerate.GetToken();
string responseString = "";
string uri = "https://indexing.googleapis.com/v3/urlNotifications/metadata?url=https%3A%2F%2Fwww.WEBSITEHERE.nl%2F";
WebRequest request = WebRequest.Create(uri);
request.PreAuthenticate = true;
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "GET";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
responseString = reader.ReadToEnd();
}
Console.WriteLine(responseString);
Console.ReadKey();
}
}