本文使用C#開發Winform應用程序,經過調用<WebXml/>(URL:http://www.webxml.com.cn)的WebService服務WeatherWS來獲取天氣預報數據。本程序所使用的Web服務的URL爲:http://ws.webxml.com.cn/WebServices/WeatherWS.asmx,此服務爲「2400多個城市天氣預報Web服務」。web
開發環境說明:函數
本程序經過「添加Web引用」和「使用WSDL文件」兩種方式實現WebService服務的調用。工具
首先,新建一個WinForm應用程序,在「解決方案管理器」中爲該工程添加Web引用:右擊工程-->添加服務引用,彈出以下「服務引用設置」對話框:開發工具
點擊該對話框「添加Web引用」按鈕,彈出「Web引用」對話框,在其中的URL處輸入WeatherWS服務地址(http://ws.webxml.com.cn/WebServices/WeatherWS.asmx),點擊轉到「-->」按鈕,修改Web引用名爲「WebRefWeather」,以下圖所示:spa
此時,在須要獲取天氣信息的地方添加「獲取天氣核心代碼」便可。我是在"按鈕響應函數"中添加的,代碼以下:代理
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); }
程序運行後,點擊按鈕,便可顯示天氣信息,以下圖所示:code
此方法爲經過使用VS工具由Web服務URL(http://ws.webxml.com.cn/WebServices/WeatherWS.asmx)或者本地的WeatherWS.asmx文件獲得wsdl文件;而後由wsdl文件生成cs文件,即Web服務代理類,最後經過使用此類獲取天氣數據。即一下幾步:orm
首先,看一下disco工具的幫助,以下圖所示:xml
經過以下命令,獲得wsdl文件:blog
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便可,以下圖所示:
添加以後,再啓動程序,程序即會啓動成功。而後,點擊按鈕,即會像上一個方法同樣顯示天氣信息,以下圖所示: