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

标签 c# .net google-custom-search

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

相关文章:

c# - 在 Microsoft Bot Framework V3 中触发系统消息

c# - 使用不同的参数多次调用 BackgroundWorker.RunWorkerAsync()

google-oauth - 带有 Google 自定义搜索功能的 Google 附加链接搜索框

c# - 派生类中的静态构造函数首先被调用,然后是基类

c# - 如何为 RabbitMQ 管理 HTTP API 生成 password_hash

c++ - 图像对象和图像原始数据的内容有什么区别

html - Google 自定义搜索引擎需要很长时间才能加载到网页上?

css - 使用外部 CSS 样式表自定义 Google CSE 的外观

c# - Visual Studio 中的 WriteLine 就像在 LinqPad 中一样

c# - N休眠;删除 child 会删除 parent 吗?