通过C#使用googleAPI
要使用googleAPI 来开发自己的桌面应用程序,先要做下面的准备工作:
1. 首先在下面地址http://www.google.com/apis/download.html下载the Google Web APIs Developer's Kit。
2. 然后在下面地址
https://www.google.com/accounts/NewAccount?continue=http://api.google.com/createkey&followup=http://api.google.com/createkey注册一个 license key 以使用google提供的搜索服务。
新建一个Google Search应用程序
1. 新建一个Windows From 项目命名为Google Search。
2. 添加Web引用,以便使用google web services。具体做法是将下载的the Google Web APIs Developer's Kit中的GoogleSearch.wsdl文件放入本地的服务器上,然后在VS中右键点击资源管理器中的引用,再选择添加Web引用,然后输入GoogleSearch.wsdl文件在本机服务器上的地址http://localhost/GoogleSearch.wsdl,更改Web引用名为GoogleSearch后,点击添加引用后返回。
3. 进行界面设计,添加3个控件,TextBox(用于输入关键字),Button(用于提交信息),RichTextBox(用于显示搜索结果信息)。
4. 编写事件处理。
1) 添加命名空间。using Google_Search.googlesearch;
2) 双击Button控件,在Button的事件处理中添加下面的代码:
try
{
GoogleSearchService s = new GoogleSearchService(); //建立一个搜索服务。
GoogleSearchResult r = s.doGoogleSearch("NGYfW7dQFHKshnXPwvctLsaipk03YK2x", textBox1.Text, 0, 10, true, "", true, "", "", ""); //使用doGoogleSearch方法取得搜索结果。
ResultElement[] re = r.resultElements; //将结果传入一个ResultElement数组。
foreach (ResultElement n in re)
{
richTextBox1.AppendText(n.title+"\r"); //显示标题。
richTextBox1.AppendText(n.snippet+"\r"); //显示包含关键字摘要信息。
richTextBox1.AppendText(n.URL); //显示网页地址。
richTextBox1.AppendText("\n\r\r");
}
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}
3) 按ctrl+F5就能测试应用程序了。