第五步,编写程序代码。下面我们为每个按钮的编写其消息相应函数。
对于第一个按钮"开始搜索!",它的消息响应函数完成的功能如下:首先创建一个Google搜索的对象,然后根据你所输入的许可证密钥以及你要搜索的内容调用doGoogleSearch函数。不过我们在程序中只运用了该函数的一种简单的搜索功能,你可以试着使用不同的参数来完成更高级的搜索功能。最后从搜索的结果中分离出返回的结果数这一项并显示在程序的窗体中。该函数的实现如下:
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click ' 创建一个Google搜索对象 Dim s As New Google.GoogleSearchService() Try ' 调用搜索功能 Dim r As Google.GoogleSearchResult = s.doGoogleSearch(txtLicenseKey.Text, txtSearchTerm.Text, 0, 1, False, "", False, "", "", "") ' 从搜索的结果中分离出返回的结果数这一项并显示在程序的窗体中 Dim estResults As Integer = r.estimatedTotalResultsCount lblSearchResults.Text = CStr(estResults) Catch ex As System.Web.Services.Protocols.SoapException MsgBox(ex.Message) End Try End Sub | 对于"缓存查询!"这个按钮的消息响应函数,其完成的功能是获取缓存页面的大小。它调用的方法为doGetCachedPage,通过该方法,程序可以获得缓存页面的字节数,然后根据该字节数显示缓存页面的大小。 其函数实现代码如下:
Private Sub btnCache_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCache.Click ' 创建一个Google搜索对象 Dim s As New Google.GoogleSearchService() Try ' 调用doGetCachedPage方法并获取缓存字节数 Dim bytes() As System.Byte = s.doGetCachedPage(txtLicenseKey.Text, txtCachePage.Text) ' 显示缓存页面的大小 lblCacheResults.Text = CStr(bytes.Length) Catch ex As System.Web.Services.Protocols.SoapException MsgBox(ex.Message) End Try End Sub | 对于"拼写检查!"按钮的消息响应函数,它完成的功能则是对用户的输入进行拼写检查。使用过Google搜索功能的人都知道,如果你一不小心输入错误的话,它会提示你正确的输入,这是因为它调用了内部的拼写检查功能。比如,我在Google中输入"Comparision of Chinese culture and western culture"的话,Google会提示我是否要搜索"Comparison of Chinese culture and western culture",一经它的提醒我才发现我把"Comparison"给拼错了。所以该按钮的消息响应函数调用了doSpellingSuggestion方法,调用之后如果获得了相应的拼写建议,则往往是你发生了拼写方面的错误了,并显示在窗体的文本框控件中。其函数的代码实现如下:
Private Sub btnSpell_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSpell.Click ' 创建一个Google搜索对象 Dim s As New Google.GoogleSearchService() Try ' 调用doSpellingSuggestion方法 Dim suggestion As String = s.doSpellingSuggestion(txtLicenseKey.Text, txtSpell.Text) ' 如果右拼写建议的信息,则显示之 If suggestion Is Nothing Then lblSpellResults.Text = "" Else lblSpellResults.Text = suggestion End If Catch ex As System.Web.Services.Protocols.SoapException MsgBox(ex.Message) End Try End Sub |
第六步:运行程序。程序的运行结果图示如下:
 图4 |
三.小结:
本文介绍了如何运用VB.net来访问Google的Web服务的方法,当然你也可以用其他的语言,比如C#或是Java来开发此类应用。通过添加Web服务的引用,开发者可以像是开发本机程序一样的开发Web服务程序,所以说运用VS.net开发工具大大简化了开发人员的工作。不过本程序只是一个简单的示例程序,要是你要开发出更高级的应用,不妨去参考开发者工具箱中的详细说明文档。通过它,我想你一定可以开发出很好的Google的Web服务的应用。
|
|