我刚发现Google APIs Client Library for .NET,但由于缺乏文档,我很难弄明白。如何使用Google Custom Search API for .NET进行搜索?
我试图做一个简单的测试,进行自定义搜索,我已经等中望去,在以下命名空间:
Google.Apis.Customsearch.v1.Data.Query
我试图创建一个查询对象,并填写SearchTerms ,但我怎样才能从该查询中获取结果?
我刚发现Google APIs Client Library for .NET,但由于缺乏文档,我很难弄明白。如何使用Google Custom Search API for .NET进行搜索?
我试图做一个简单的测试,进行自定义搜索,我已经等中望去,在以下命名空间:
Google.Apis.Customsearch.v1.Data.Query
我试图创建一个查询对象,并填写SearchTerms ,但我怎样才能从该查询中获取结果?
看看API Reference 使用代码google-api-dotnet-client
CustomsearchService svc = new CustomsearchService();
string json = File.ReadAllText("jsonfile",Encoding.UTF8);
Search googleRes = null;
ISerializer des = new NewtonsoftJsonSerializer();
googleRes = des.Deserialize<Search>(json);
或
CustomsearchService svc = new CustomsearchService();
Search googleRes = null;
ISerializer des = new NewtonsoftJsonSerializer();
using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
googleRes = des.Deserialize<Search>(fileStream);
}
与流也可以读出的webClient
或HttpRequest
,如你所愿
首先, ,您需要确保您已经生成了您的API密钥和CX。我假设你已经做了已经,否则,你可以在这些地方做:
一旦你拥有了这些,这里是执行搜索和转储所有的标题/链接一个简单的控制台应用程序:
static void Main(string[] args)
{
WebClient webClient = new WebClient();
string apiKey = "YOUR KEY HERE";
string cx = "YOUR CX HERE";
string query = "YOUR SEARCH HERE";
string result = webClient.DownloadString(String.Format("https://www.googleapis.com/customsearch/v1?key={0}&cx={1}&q={2}&alt=json", apiKey, cx, query));
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> collection = serializer.Deserialize<Dictionary<string, object>>(result);
foreach (Dictionary<string, object> item in (IEnumerable)collection["items"])
{
Console.WriteLine("Title: {0}", item["title"]);
Console.WriteLine("Link: {0}", item["link"]);
Console.WriteLine();
}
}
由于你可以看到,我将一个通用的JSON反序列化转换为一个字典,而不是强类型的。这是为了方便,因为我不想创建一个实现搜索结果模式的类。采用这种方法,有效载荷是嵌套的键值对集合。你最感兴趣的是项目集合,这是搜索结果(我假设的第一页)。我只能访问“标题”和“链接”属性,但还有很多可以从文档中看到或在调试器中检查。
我正在寻找如何使用[Google API的.NET客户端库](http://code.google.com/p/google-api-dotnet-客户端/ wiki/API#CustomSearch_API)。无论如何thanx ..这也有帮助。 – Darshana
您可以从Getting Started with the API开始。
我的不好,我的第一个答案是没有使用Google API。
作为一个先决条件,你需要得到Google API client library
(特别是,你将需要引用Google.Apis.dll在您的项目)。现在,假设你有你的API密钥和CX,这里是得到的结果相同的代码,但是现在使用实际的API:
string apiKey = "YOUR KEY HERE";
string cx = "YOUR CX HERE";
string query = "YOUR SEARCH HERE";
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 result in search.Items)
{
Console.WriteLine("Title: {0}", result.Title);
Console.WriteLine("Link: {0}", result.Link);
}
Google.Apis.Customsearch.v1客户端库 http://www.nuget.org/packages/Google.Apis.Customsearch.v1/
您的“API参考”链接已死亡... – billy