2013-02-14 61 views
7

我想在我的.NET項目中使用Google自定義搜索API。 我有我公司提供的API密鑰。 我使用我的Google帳戶創建了自定義搜索引擎,並複製了'cx'值。在.NET中使用Google自定義搜索API的步驟

我使用下面的代碼:

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); 
} 

在這裏,我得到下面的異常,在獲取():

次Google.Apis.Requests.RequestError 訪問未配置[403] 錯誤[留言[訪問未配置]地址[ - ]原因[accessNotConfigured]域[usageLimits]

是否需要CX參數? 我是否收到錯誤信息,因爲我使用的是我的公司提供的密鑰,並使用我的Google帳戶中的 自定義搜索引擎的CX參數?

是否有任何其他方式獲得'cx'?我們不想顯示Google AD。

非常感謝您提前尋求幫助。

回答

10

我不確定你是否仍然對此感興趣。

要獲得沒有廣告的結果,您需要爲此付費。 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); 
     } 

希望這有助於

8

代替,

var search = listRequest.Fetch(); 

但現在它不支持fetch()方法,而你需要使用execute()方法。

var search = listRequest.Execute(); 
+1

請參閱http://hintdesk.com/c-how-to-use-google-custom-search-api/ – Cel 2015-06-01 11:30:44

相關問題