C#調用WebService實現天氣預報

本文使用Winform (C#)調用互聯網上公開的WebServices(http://www.webxml.com.cn/WebServices/WeatherWebService.asmx)來實現天氣預報,該天氣預報 Web 服務,數據來源於中國氣象局 http://www.cma.gov.cn/ ,數據每2.5小時左右自動更新一次,準確可靠。包括 340 多箇中國主要城市和 60 多個國外主要城市三日內的天氣預報數據。

程序效果:

實現步驟:

1、引入Web服務。在VS中項目上右擊→添加服務引用。

 

2、在彈出的添加服務引用窗口,錄入web服務地址和引用後的命名空間。

3、佈置winform窗體界面,實現代碼。核心代碼如下:

 

  1. private void button1_Click_1(object sender, EventArgs e)  
  2.   {  
  3.       Weather.WeatherWebServiceSoapClient w = new Weather.WeatherWebServiceSoapClient("WeatherWebServiceSoap");  
  4.       //把webservice當做一個類來操作  
  5.       string[] s = new string[23];//聲明string數組存放返回結果  
  6.       string city = this.textBox1.Text.Trim();//獲得文本框錄入的查詢城市  
  7.       s = w.getWeatherbyCityName(city);  
  8.       //以文本框內容爲變量實現方法getWeatherbyCityName  
  9.       if (s[8] == "")  
  10.       {  
  11.           MessageBox.Show("暫時不支持您查詢的城市");  
  12.       }  
  13.       else 
  14.       {  
  15.           pictureBox1.Image = Image.FromFile(@"d:\p_w_picpath\" + s[8] + "");  
  16.           this.label4.Text =s[1]+" "+s[6];  
  17.           textBox2.Text = s[10];     
  18.       }  
  19.  
  20.   } 

 

4、天氣圖標可至【http://www.webxml.com.cn/p_w_picpaths/weather.zip】下載。

5、Web服務的各方法參數直接訪問【http://www.webxml.com.cn/WebServices/WeatherWebService.asmx】查詢,從而實現其它豐富功能,如未來天氣預報等。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章