C#調用WebService實現天氣預報


http://zhangkui.blog.51cto.com/1796259/497324/

本文使用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:\image\" + s[8] + "");  
  16.           this.label4.Text =s[1]+" "+s[6];  
  17.           textBox2.Text = s[10];     
  18.       }  
  19.  
  20.   } 

 

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

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


 

s = w.getWeatherbyCityName(city);
這行報“服務器無法處理請求。 ---> 未將對象引用設置到對象的實例。”錯誤怎么處理

添加服務引用->高級->添加web服務引用

 后台重新using引用 定義w對象時 博主的方法不能用 weather.cn.com.webxml.www.WeatherWebService w = new weather.cn.com.webxml.www.WeatherWebService(); 這樣就行了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM