概述
本文使用C#開發Winform應用程序,通過調用<WebXml/>(URL:http://www.webxml.com.cn)的WebService服務WeatherWS來獲取天氣預報數據。本程序所使用的Web服務的URL為:http://ws.webxml.com.cn/WebServices/WeatherWS.asmx,此服務為“2400多個城市天氣預報Web服務”。
開發環境說明:
- 系統平台:Windows 7(32bit);
- 開發工具:VS2010;
實現過程
本程序通過“添加Web引用”和“使用WSDL文件”兩種方式實現WebService服務的調用。
1、添加Web引用
首先,新建一個WinForm應用程序,在“解決方案管理器”中為該工程添加Web引用:右擊工程-->添加服務引用,彈出如下“服務引用設置”對話框:
點擊該對話框“添加Web引用”按鈕,彈出“Web引用”對話框,在其中的URL處輸入WeatherWS服務地址(http://ws.webxml.com.cn/WebServices/WeatherWS.asmx),點擊轉到“-->”按鈕,修改Web引用名為“WebRefWeather”,如下圖所示:
此時,在需要獲取天氣信息的地方添加“獲取天氣核心代碼”即可。我是在"按鈕響應函數"中添加的,代碼如下:
WebRefWeather.WeatherWS weather = new WebRefWeather.WeatherWS(); string[] str = new string[32]; try { str = weather.getWeather("北京", ""); MessageBox.Show(str[0] + "\n" + str[1] + "\n" + str[2] + "\n" + str[4] + "\n" + str[5], "天氣信息"); } catch (Exception ex) { MessageBox.Show(ex.Message); }
程序運行后,點擊按鈕,即可顯示天氣信息,如下圖所示:
2、使用WSDL文件
此方法為通過使用VS工具由Web服務URL(http://ws.webxml.com.cn/WebServices/WeatherWS.asmx)或者本地的WeatherWS.asmx文件得到wsdl文件;然后由wsdl文件生成cs文件,即Web服務代理類,最后通過使用此類獲取天氣數據。即一下幾步:
- asmx文件 --> wsdl文件(VS2010工具:disco);
- wsdl文件 --> cs文件(VS2010工具:wsdl);
首先,看一下disco工具的幫助,如下圖所示:
通過如下命令,得到wsdl文件:
disco http://ws.webxml.com.cn/WebServices/WeatherWS.asmx
如下圖所示:
然后,通過wsdl命令由wsdl文件生成cs文件,wsdl命令幫助如下:
生成cs文件的命令如下:
wsdl /l:cs /n:NS_WeatherWS /out:WeatherWS.cs WeatherWS.wsdl
即:
此時,將cs文件加入到新建的Winform工程中,再在按鈕的響應函數中加入如下核心代碼:
NS_WeatherWS.WeatherWS weather = new NS_WeatherWS.WeatherWS(); string[] str = new string[32]; try { str = weather.getWeather("北京", ""); MessageBox.Show(str[0] + "\n" + str[1] + "\n" + str[2] + "\n" + str[4] + "\n" + str[5], "天氣信息"); } catch (Exception ex) { MessageBox.Show(ex.Message); }
此時,運行程序,會出現如下錯誤:
命名空間“System.Web”中不存在類型或命名空間名稱“Services”。是否缺少程序集?
解決辦法:在該工程中添加DotNet引用System.Web.Services即可,如下圖所示:
添加之后,再啟動程序,程序即會啟動成功。然后,點擊按鈕,即會像上一個方法一樣顯示天氣信息,如下圖所示: