我正在尝试在我的 .NET 项目中使用 Google 自定义搜索 API。 我有我公司提供的 API key 。 我已经使用我的 Google 帐户创建了一个自定义搜索引擎并复制了“cx”值。
我正在使用以下代码:
string apiKey = "My company Key";
string cx = "Cx";
string query = tbSearch.Text;
WebClient webClient = new WebClient();
webClient.Headers.Add("user-agent", "Only a test!");
string result = webClient.DownloadString(String.Format("https://www.googleapis.com/customsearch/v1?key={0}&cx={1}&q={2}&alt=json", apiKey, cx, query));
我收到以下错误:“远程服务器返回错误:(403) 禁止访问。”
我也试过下面的代码:
Google.Apis.Customsearch.v1.CustomsearchService svc = new Google.Apis.Customsearch.v1.CustomsearchService();
svc.Key = apiKey;
Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = svc.Cse.List(query);
listRequest.Cx = cx;
Google.Apis.Customsearch.v1.Data.Search search = listRequest.Fetch();
foreach (Google.Apis.Customsearch.v1.Data.Result result1 in search.Items)
{
Console.WriteLine("Title: {0}", result1.Title);
Console.WriteLine("Link: {0}", result1.Link);
}
在这里,我在 Fetch() 中得到以下异常:
Google.Apis.Requests.RequestError 访问未配置 [403] 错误 [消息[访问未配置] 位置[-] 原因[accessNotConfigured] 域[usageLimits]
是否需要 CX 参数? 我收到错误是因为我正在使用我公司提供的 key 并使用来自 使用我的 Google 帐户自定义搜索引擎?
是否有任何其他方式获得“cx”?我们不想展示 Google 广告。
非常感谢您的帮助。
最佳答案
我不确定你是否仍然对此感兴趣。
要在没有广告的情况下获得结果,您需要为此付费。 Info @ Google
是的,cx 是必需的,因为它指定了您要用于搜索的谷歌自定义搜索引擎。 您可以从 This google page 创建自定义搜索引擎
这是检索当前 api 版本 1.3.0-beta 的搜索结果的当前代码
string apiKey = "Your api key";
string cx = "Your custom search engine id";
string query = "Your query";
var svc = new Google.Apis.Customsearch.v1.CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey });
var listRequest = svc.Cse.List(query);
listRequest.Cx = cx;
var search = listRequest.Fetch();
foreach (var result in search.Items)
{
Response.Output.WriteLine("Title: {0}", result.Title);
Response.Output.WriteLine("Link: {0}", result.Link);
}
希望对你有帮助
关于c# - 在 .NET 中使用 Google 自定义搜索 API 的步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14880921/