【问题标题】:Steps for using Google custom search API in .NET在 .NET 中使用 Google 自定义搜索 API 的步骤
【发布时间】:2013-02-14 17:46:30
【问题描述】:

我正在尝试在我的 .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));

我收到以下错误:“远程服务器返回错误:(403) Forbidden。”

我也试过下面的代码:

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 参数? 我收到错误是因为我正在使用我公司提供的密钥并使用来自的 CX 参数 使用我的 Google 帐户的自定义搜索引擎?

还有其他获取“cx”的方法吗?我们不想展示 Google AD。

非常感谢您的帮助。

【问题讨论】:

    标签: c# .net google-custom-search


    【解决方案1】:

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

    要获得没有广告的结果,您需要付费。 Info @ Google

    是的,cx 是必需的,因为它指定了您要用于搜索的 google 自定义搜索引擎。 你可以从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);
            }
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      而不是,

      var search = listRequest.Fetch();
      

      但是现在不支持 Fetch() 方法,需要使用 Execute() 方法。

      var search = listRequest.Execute();
      

      【讨论】:

        【解决方案3】:
        var listRequest = svc.Cse.List(query);
        

        错误!!! 你应该使用:

        var listRequest = svc.Cse.List();
        

        然后:

        listRequest.Q=query
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多