Raj*_*Raj 7 .net c# google-custom-search
我想在我的.NET项目中使用Google自定义搜索API.我有一个由我公司提供的API密钥.我使用自己的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));
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:"远程服务器返回错误:(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);
}
Run Code Online (Sandbox Code Playgroud)
这里我在Fetch()中得到以下异常:
Google.Apis.Requests.RequestError未配置访问[403]错误[消息[未配置访问]位置[ - ]原因[accessNotConfigured]域[usageLimits]
是否需要CX参数?我是否收到错误,因为我使用的是我公司提供的密钥,并使用我的Google帐户使用自定义搜索引擎中的CX参数?
有没有其他方式获得'cx'?我们不想展示Google广告.
非常感谢您提前寻求帮助.
Mah*_*him 10
我不确定你是否还对此感兴趣.
要获得没有广告的结果,您需要为此付费. Info @ Google
是的,cx是必需的,因为它指定了您要用于搜索的Google自定义搜索引擎.您可以从此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);
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
小智 10
代替,
var search = listRequest.Fetch();
Run Code Online (Sandbox Code Playgroud)
但是现在它不支持Fetch()方法,而是需要使用Execute()方法.
var search = listRequest.Execute();
Run Code Online (Sandbox Code Playgroud)
小智 6
var listRequest = svc.Cse.List(query);
Run Code Online (Sandbox Code Playgroud)
错误 !!!你应该使用:
var listRequest = svc.Cse.List();
Run Code Online (Sandbox Code Playgroud)
进而 :
listRequest.Q=query
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18318 次 |
| 最近记录: |