在中使用Google自定义搜索API的步骤.NET

本文关键字:API NET 搜索 自定义 Google | 更新日期: 2023-09-27 17:59:38

我正在尝试在我的中使用Google自定义搜索API。NET项目。我有一个API密钥由我的公司提供。我使用我的谷歌账户创建了一个自定义搜索引擎,并复制了"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()中得到以下异常:

谷歌。Apis。请求。请求错误未配置访问[403]错误[Message[Access Not Configured]Location[-]Reason[accessNotConfigured]Domain[usageLimits]

是否需要CX参数?我收到错误是因为我使用了公司提供的密钥,并使用了使用我的谷歌帐户自定义搜索引擎?

还有其他方法可以得到cx吗?我们不想显示谷歌广告。

事先非常感谢您的帮助。

在中使用Google自定义搜索API的步骤.NET

我不确定您是否仍然对此感兴趣。

要在没有广告的情况下获得结果,你需要为此付费。信息@谷歌

是的,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 search = listRequest.Execute();
var listRequest = svc.Cse.List(query);

错误!!!您应该使用:

var listRequest = svc.Cse.List();

然后:

listRequest.Q=query