C# 在.NET中使用Google自定义搜索API的步骤
我正在尝试在我的.NET项目中使用Google自定义搜索API。 我有我公司提供的API密钥。 我已经使用我的谷歌账户创建了一个自定义搜索引擎,并复制了“cx”值 我正在使用以下代码:C# 在.NET中使用Google自定义搜索API的步骤,c#,.net,google-custom-search,C#,.net,Google Custom Search,我正在尝试在我的.NET项目中使用Google自定义搜索API。 我有我公司提供的API密钥。 我已经使用我的谷歌账户创建了一个自定义搜索引擎,并复制了“cx”值 我正在使用以下代码: string apiKey = "My company Key"; string cx = "Cx"; string query = tbSearch.Text; WebClient webClient = new WebClient(); webClient.Headers.Add("user-agent",
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.api.Requests.RequestError
未配置访问权限[403]
错误[消息[Access Not Configured]位置[-]原因[accessNotConfigured]域[usageLimits]
是否需要CX参数?
我是否因为使用公司提供的密钥和中的CX参数而出现错误
自定义搜索引擎使用我的谷歌帐户
有没有其他方式获得“cx”?我们不想显示谷歌广告
提前非常感谢您的帮助。我不确定您是否仍对此感兴趣 要想在没有广告的情况下获得效果,你需要为此付费。 是的,cx是必需的,因为它指定了要用于搜索的google自定义搜索引擎。 您可以从中创建自定义搜索引擎 下面是检索当前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);
}
希望这有帮助,而不是
var search = listRequest.Fetch();
但现在它不支持Fetch()方法,而是需要使用Execute()方法
错误!!!
你应使用:
var listRequest = svc.Cse.List();
然后:
listRequest.Q=query
var listRequest = svc.Cse.List();
listRequest.Q=query