加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C# 天气预报

发布时间:2020-12-16 01:14:11 所属栏目:百科 来源:网络整理
导读:本文通过一个完整的实例,讲解如何通过访问中国天气网提供的API接口,实现天气预报功能,仅供学习分享使用,如有不足之处,还请指正。 涉及知识点 实现天气预报功能的相关知识点: 天气预报接口【提供风向,风速等功能】:http://www.weather.com.cn/data/sk

本文通过一个完整的实例,讲解如何通过访问中国天气网提供的API接口,实现天气预报功能,仅供学习分享使用,如有不足之处,还请指正。

涉及知识点

实现天气预报功能的相关知识点:

  • 天气预报接口【提供风向,风速等功能】:http://www.weather.com.cn/data/sk/101120201.html
  • 天气预报接口【提供天气基础功能】:http://www.weather.com.cn/data/cityinfo/101120201.html
  • 新浪网的接口【其中city后的是城市的名称转码】http://php.weather.sina.com.cn/xml.php?city=%B1%B1%BE%A9&password=DJOYnieT8234jlsK&day=0
  • HttpWebRequest/HttpWebResponse 访问网络的相关资源
  • XmlSerializer 中序列化与反序列化功能
  • Newtonsoft.Json中Json字符串的反序列化功能
  • 泛型,委托

效果图

具体如图所示:

核心代码

天气代码,对接天气API接口返回的实体类,两个接口对应两个实体类:

?

  1 using Newtonsoft.Json;
  2  System;
  3  System.Collections.Generic;
  4  System.Linq;
  5  System.Text;
  6  System.Threading.Tasks;
  7  System.Xml.Serialization;
  8 
  9 namespace DemoWeather
 10 {
 11     /// <summary>
 12     /// 城市基础天气信息类
 13     </summary>
 14     [Serializable]
 15     public class CWeather
 16     {
 17         [JsonProperty("weatherinfo")]
 18         public CWeatherInfo WeatherInfo { get; set; }
 19     }
 20 
 21  22      CWeatherInfo
 23  24         [JsonProperty(city 25         string City {  26 
 27         [JsonProperty(cityid 28         string CityId {  29 
 30          31          气温1
 32          33         [JsonProperty(temp1 34         string Temp1 {  35 
 36          37          气温2
 38          39         [JsonProperty(temp2 40         string Temp2 {  41 
 42          43          天气情况
 44          45         [JsonProperty(weather 46         string Weather {  47 
 48         [JsonProperty(img1 49         string Img1 {  50 
 51         [JsonProperty(img2 52         string Img2 {  53 
 54          55          更新时间
 56          57         [JsonProperty(ptime 58         string PTime {  59 
 60  61 
 62      63      城市基础天气信息类(另外一个)
 64      65  66      DWeather
 67  68         [JsonProperty( 69         public DWeatherInfo WeatherInfo {  70  71 
 72  73      DWeatherInfo {
 74         [JsonProperty( 75          76 
 77         [JsonProperty( 78          79 
 80          81          82          83         [JsonProperty(temp 84         string Temp {  85 
 86          87          风向
 88          89         [JsonProperty(WD 90         string WD {  91 
 92          93          风速
 94          95         [JsonProperty(WS 96         string WS {  97 
 98          99          相对湿度
100         101         [JsonProperty(SD102         string SD { 103 
104         105          风力
106         107         [JsonProperty(WSE108         string WSE { 109 
110         111         112         113         [JsonProperty(time114         string Time { 115 
116         117          是否有雷达图(1表示有雷达图)
118         119         [JsonProperty(isRadar120         string IsRadar { 121 
122         123          雷达图地址(AZ9532为青岛雷达)
124         125         [JsonProperty(Radar126         string Radar { 127 
128         129         /// 
130         131         [JsonProperty(njd132         string Njd { 133 
134         [JsonProperty(qy135         string Qy { 136 
137         [JsonProperty(rain138         string Rain { 139 
140 141 
142     143      新浪天气预报API实体类
144     145 146     [XmlRoot(Profiles147      SWeather {
148 
149         [JsonProperty(Weather150         [XmlElementAttribute(151         public SWeatherInfo WeatherInfo { 152 153 
154      SWeatherInfo {
155 
156         157          对应的查询城市
158         159         [JsonProperty(160         [XmlElementAttribute(161         162 
163         164          白天天气情况
165         166         [JsonProperty(status1167         [XmlElementAttribute(168         string Status1 { 169 
170         171          夜间天气情况
172         173         [JsonProperty(status2174         [XmlElementAttribute(175         string Status2 { 176 
177         178          白天天气情况拼音
179         180         [JsonProperty(figure1181         [XmlElementAttribute(182         string Figure1 { 183 
184         185          夜间天气情况拼音
186         187         [JsonProperty(figure2188         [XmlElementAttribute(189         string Figure2 { 190 
191         192          白天风向
193         194         [JsonProperty(direction1195         [XmlElementAttribute(196         string Direction1 { 197 
198         199          夜晚风向
200         201         [JsonProperty(direction2202         [XmlElementAttribute(203         string Direction2 { 204 
205         206          白天风力
207         208         [JsonProperty(power1209         [XmlElementAttribute(210         string Power1 { 211 
212         213          夜间风力
214         215         [JsonProperty(power2216         [XmlElementAttribute(217         string Power2 { 218 
219         220          白天温度
221         222         [JsonProperty(temperature1223         [XmlElementAttribute(224         string Temperature1 { 225 
226         227          夜间温度
228         229         [JsonProperty(temperature2230         [XmlElementAttribute(231         string Temperature2 { 232 
233         234          体感指数
235         236         [JsonProperty(ssd237         [XmlElementAttribute(238         string Ssd { 239 
240         241          白天体感温度
242         243         [JsonProperty(tgd1244         [XmlElementAttribute(245         string Tgd1 { 246 
247         248          夜间体感温度
249         250         [JsonProperty(tgd2251         [XmlElementAttribute(252         string Tgd2 { 253 
254         255          紫外线强度
256         257         [JsonProperty(zwx258         [XmlElementAttribute(259         string Zwx { 260 
261         262          空调指数
263         264         [JsonProperty(ktk265         [XmlElementAttribute(266         string Ktk { 267 
268         269          污染指数
270         271         [JsonProperty(pollution272         [XmlElementAttribute(273         string Pollution { 274 
275         276          洗车指数
277         278         [JsonProperty(xcz279         [XmlElementAttribute(280         string Xcz { 281 
282         283          综合指数这个我不确定
284         285         [JsonProperty(zho286         [XmlElementAttribute(287         string Zho { 288 
289         290          没猜出来是什么指数,没有数值
291         292         [JsonProperty(diy293         [XmlElementAttribute(294         string Diy { 295 
296         297          同上
298         299         [JsonProperty(fas300         [XmlElementAttribute(301         string Fas { 302 
303         304          穿衣指数
305         306         [JsonProperty(chy307         [XmlElementAttribute(308         string Chy { 309 
310         311          zho的说明,然而zho是什么指数我也不确定
312         313         [JsonProperty(zho_shuoming314         [XmlElementAttribute(315         string Zho_shuoming { 316 
317         318         319         320         [JsonProperty(diy_shuoming321         [XmlElementAttribute(322         string Diy_shuoming { 323 
324         325         326         327         [JsonProperty(fas_shuoming328         [XmlElementAttribute(329         string Fas_shuoming { 330 
331         332          穿衣指数说明
333         334         [JsonProperty(chy_shuoming335         [XmlElementAttribute(336         string Chy_shuoming { 337 
338         339          污染程度
340         341         [JsonProperty(pollution_l342         [XmlElementAttribute(343         string Pollution_l { 344 
345         346          紫外线指数概述
347         348         [JsonProperty(zwx_l349         [XmlElementAttribute(350         string Zwx_l { 351 
352         353          体感指数概述
354         355         [JsonProperty(ssd_l356         [XmlElementAttribute(357         string Ssd_l { 358 
359         360          这个不知道
361         362         [JsonProperty(fas_l363         [XmlElementAttribute(364         string Fas_l { 365 
366         367         368         369         [JsonProperty(zho_l370         [XmlElementAttribute(371         string Zho_l { 372 
373         374          穿衣指数概述(可理解为穿衣建议)
375         376         [JsonProperty(chy_l377         [XmlElementAttribute(378         string Chy_l { 379 
380         381          空调指数概述
382         383         [JsonProperty(ktk_l384         [XmlElementAttribute(385         string Ktk_l { 386 
387         388          洗车指数概述
389         390         [JsonProperty(xcz_l391         [XmlElementAttribute(392         string Xcz_l { 393 
394         395         396         397         [JsonProperty(diy_l398         [XmlElementAttribute(399         string Diy_l { 400 
401         402          污染指数详细说明
403         404         [JsonProperty(pollution_s405         [XmlElementAttribute(406         string Pollution_s { 407 
408         409          紫外线详细说明
410         411         [JsonProperty(zwx_s412         [XmlElementAttribute(413         string Zwx_s { 414 
415         416          体感详细说明
417         418         [JsonProperty(ssd_s419         [XmlElementAttribute(420         string Ssd_s { 421 
422         423          空调指数详细说明
424         425         [JsonProperty(ktk_s426         [XmlElementAttribute(427         string Ktk_s { 428 
429         430          洗车详细说明
431         432         [JsonProperty(xcz_s433         [XmlElementAttribute(434         string Xcz_s { 435 
436         437          感冒指数
438         439         [JsonProperty(gm440         [XmlElementAttribute(441         string Gm { 442 
443         444          感冒指数概述
445         446         [JsonProperty(gm_l447         [XmlElementAttribute(448         string Gm_l { 449 
450         451          感冒指数详细说明
452         453         [JsonProperty(gm_s454         [XmlElementAttribute(455         string Gm_s { 456 
457         458          运动指数
459         460         [JsonProperty(yd461         [XmlElementAttribute(462         string Yd { 463 
464         465          运动指数概述
466         467         [JsonProperty(yd_l468         [XmlElementAttribute(469         string Yd_l { 470 
471         472          运动指数详细说明
473         474         [JsonProperty(yd_s475         [XmlElementAttribute(476         string Yd_s { 477 
478         479          天气数据日期
480         481         [JsonProperty(savedate_weather482         [XmlElementAttribute(483         string Savedate_weather { 484 
485         486          生活数据日期
487         488         [JsonProperty(savedate_life489         [XmlElementAttribute(490         string Savedate_life { 491 
492         493          指数数据日期
494         495         [JsonProperty(savedate_zhishu496         [XmlElementAttribute(497         string Savedate_zhishu { 498 
499         500         501         502         [JsonProperty(udatetime503         [XmlElementAttribute(504         string Udatetime { 505 
506 507 }
View Code


国家代码,对应级联菜单的实体类:

  6 
  8   9      10      国家类
 12      Country {
 13 
 14          15          id
 16          17         string Id {  18 
 19          20          国家名
 21          22         string Name {  23          24          省份列表
 25          26         public List<Province> ProvinceList {  27 
override string ToString()
 29         {
 30             return this.Name;
 31         }
 32  33 
 34      35      省份类
 36      37      Province
 38  39          40          省份名称
 41          42          43 
 45          省份ID
 46          47          48 
 49          50          城市列表
 51         public List<City> CityList {  54          55  56              57  58  60      61      城市类
 63      City {
 64         
 65          66          城市名称
 67          68          69 
 70          71          城市Id
 72          73          74 
 75          76          城市里面的城区列表
 77         public List<Urban> UrbanList {  80          81  82              83  84  86      87      城区,县城
 88      89      Urban {
 90         
 91          城区名称
 94          95 
 96          97          城区ID
 99         100 
101         102 103             104 105 106 }
View Code

访问接口类代码如下:

 1  2  3  4  System.IO;
 5  6  System.Net;
 7  8  System.Threading;
 9 10 11 
12 13 14     15      访问天气API接口
16     17      WeatherAccess
18 19         20          获取天气站点的信息
21         22         <typeparam name="T">返回类的信息</typeparam>
23         <param name="url"><网址/param>
24         <returns></returns>
25         static T CallWeatherWebSite<T>( url)
26 27             HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
28             request.Method = GET;
29             request.Accept = text/json30             HttpWebResponse response = request.GetResponse() as HttpWebResponse;
31             string strJson = .Empty;
32             while (true)
33             {
34                 if (response.StatusCode == HttpStatusCode.OK)
35                 {
36                     Stream stream = response.GetResponseStream();
37                     using (StreamReader reader = new StreamReader(stream,Encoding.UTF8))
38                     {
39                         strJson = reader.ReadToEnd();
40                     }
41                     break42                 }
43                 Thread.Sleep(1000);
44             }
45             //反序列化信息
46             if (!.IsNullOrEmpty(strJson))
47 48                 T t = JsonConvert.DeserializeObject<T>(strJson);
49                 return t;
50 51             default(T);
52 53 
54         static T CallWeatherWebSite2<T>(55 56             HttpWebRequest request =57             request.Method = 58             request.Accept = text/xml59             HttpWebResponse response = request.GetResponse() 60             string strXml = 61             bool flag = false62 
63             64 65                 66 67                     Stream stream =68                     69 70                         strXml =71 72                     73 74                 Thread.Sleep(75 76             77             .IsNullOrEmpty(strXml))
78 79                 T t = new XmlHelper<T>().Deserialize2(strXml);
80                 81 82             83 84 85 }
View Code

?

?新浪网天气如下图所示【数据是实时更新】:

备注:

【上面中国天气网接口读取的数据,总感觉有些不对,不知道是不是没有更新还是咋样,权当练习了】

API接口中101110101是城市的代码,如果要查询其他城市的天气,只需要修改城市的代码即可。关于城市代码,已经整理成配置文件xml,然后通过级联菜单的方式进行加载。

-------------------------------调用webservice接口,生成验证码-------------------------------

接口网址:http://www.webxml.com.cn/WebServices/ValidateCodeWebService.asmx?wsdl

  1   WebSvcCaller
  3         
  4         private static Hashtable hshtableXML =  Hashtable();
  5 
  7           8          通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
  9          10         static XmlDocument QuerySoapWebService(String URL,String MethodName,Hashtable Pars, xmlPath)
 11  12             HttpWebRequest request = null 13             XmlDocument doc =  XmlDocument();
 14             try
 15  16                 request = (HttpWebRequest)HttpWebRequest.Create(URL);
 17                 request.Method = POST 18                 request.Accept = @"gzip,deflate 19                 request.ContentType = text/xml;charset=utf-8 20                 request.UserAgent = Jakarta Commons-HttpClient/3.1 21                 request.Credentials = CredentialCache.DefaultCredentials;
 22                 request.KeepAlive =  23                 request.Timeout = 10000 24                 byte[] data = EncodeParsToSoap(Pars,MethodName,xmlPath);
 25                 WriteRequestData(request,data);将处理成字节组的XML写到流中发送到服务端
 26             
 27                 doc = ReadXmlResponse(request.GetResponse());读取服务端返回的结果
 28               
catch (Exception ex)
 32 
 33  34             finally {
 35                 if (request != ){
 36                     request.Abort();
 37  39              doc;
 40 static Image QuerySoapWebService2(String URL,1)"> 43  44             HttpWebRequest request =  45             Image doc =  46              47  48                 request = 49                 request.Method =  50                 request.Accept =  51                 request.ContentType =  52                 request.UserAgent =  53                 request.Credentials = 54                 request.KeepAlive =  55                 request.Timeout =  56                  57                 WriteRequestData(request,1)"> 58 
 59                 doc = ReadImageResponse(request.GetResponse()); 60 
 61  62              63  64 
 66             finally
 68                  69  71  73              74  75 
 处理要发送的XML文档
 78          79         <param name="Pars">参数</param>
<param name="MethodName">方法名 81         static byte[] EncodeParsToSoap(Hashtable Pars,1)"> 82  83             XmlDocument xml =  84             if (hshtableXML.ContainsKey(MethodName))
 85             {如果已经加载过,则从缓存中读取
 86                 xml = (XmlDocument)hshtableXML[MethodName];
 87  88             else
 89             {如果还未加载则进行加载,并放入缓存
 90 
 91                 从资源文件得到文件流
 92                 Stream stream =Assembly.GetExecutingAssembly().GetManifestResourceStream(xmlPath);
 93 
 94                 xml =  95                 xml.Load(xmlPath);
 96                 hshtableXML.Add(MethodName,xml);
 97  98             if (Pars != null && Pars.Count > 0 99 100                 修改参数的值
101                 foreach (DictionaryEntry de in Pars)
103                     XmlNamespaceManager nsmgr =  XmlNamespaceManager(xml.NameTable);
104                     nsmgr.AddNamespace(soapenv",http://schemas.xmlsoap.org/soap/envelope/105                     nsmgr.AddNamespace(webhttp://WebXml.com.cn/106                     Hashtable subpars = de.Value  Hashtable;
107                     if (subpars == 108 109                         string subNode = soapenv:Envelope/soapenv:Body/web:" + MethodName + /" + de.Key.ToString();
110                         XmlNode node = xml.SelectSingleNode(subNode,nsmgr);
111                         node.InnerText = de.Value.ToString();
112 113                     114 115                         foreach (DictionaryEntry subde  subpars)
116                         {
117                             " + de.Key.ToString() +  subde.Key.ToString();
118                             XmlNode node =119                             node.InnerText = subde.Value.ToString();
120                         }
121 122 
123 124 125             将修改后的XML文件保存到流中
126             这样做还可以保证发送的XML文件也是格式化的那种形式,而不是一整行
127             如通过OuterXml获取的就是一整行,这样也可能会导致服务端解析失败,个人这次就碰到这种情况了
128             MemoryStream outStream =  MemoryStream();
129             xml.Save(outStream);
130 
131             byte[] buffer = new byte[outStream.Length];
132             byte[] temp = outStream.GetBuffer();
133             for (int i = 0; i < buffer.Length; i++134 135                 buffer[i] = temp[i];
136 137             outStream.Close();
138 
139              buffer;
142     
143         144          写到流中,发送给服务端
145         146         <param name="request">HttpWebRequest连接对象147         <param name="data">要写入连接流发给服务端的内容148         void WriteRequestData(HttpWebRequest request,1)">[] data)
149 150             request.ContentLength = data.Length;
151             Stream writer = request.GetRequestStream();
152             writer.Write(data,1)">,data.Length);
153             writer.Close();
154  读取服务端返回的结果
159         static XmlDocument ReadXmlResponse(WebResponse response)
160 161             StreamReader sr =  StreamReader(response.GetResponseStream(),Encoding.UTF8);
162             String retXml = sr.ReadToEnd();
163             sr.Close();
164             XmlDocument doc = 165             doc.LoadXml(retXml);
166             167 168 
169          Image ReadImageResponse(WebResponse response)
170 171             StreamReader sr = 172             String retXml = sr.ReadToEnd();
173             Stream stream = sr.BaseStream;
174           
175            
176             Image img = Image.FromStream(stream);
177 178              img;
179 180     }
View Code

?

 XmlHelper
 3         static List<string> getSupportProvinceResponse(XmlDocument xmlDoc)
 5             XmlNamespaceManager nsmgr =  XmlNamespaceManager(xmlDoc.NameTable);
 6             nsmgr.AddNamespace(soap 7             nsmgr.AddNamespace(xsihttp://www.w3.org/2001/XMLSchema-instance 8             nsmgr.AddNamespace(xsdhttp://www.w3.org/2001/XMLSchema 9             List<string> lstTemp = new List<();
10             XmlNode xmlNode = xmlDoc.SelectSingleNode(soap:Envelope/soap:Body11             XmlNode xmlNode1 = xmlNode.FirstChild.FirstChild;
12             foreach (XmlNode node  xmlNode1.ChildNodes) {
13                 string temp=  node.InnerText;
14                 lstTemp.Add(temp);
15 16              lstTemp;
17 18 
19          getSupportCityResponse(XmlDocument xmlDoc)
20 21             XmlNamespaceManager nsmgr = 22             nsmgr.AddNamespace(23             nsmgr.AddNamespace(24             nsmgr.AddNamespace(25             List<26             XmlNode xmlNode = xmlDoc.SelectSingleNode(27             XmlNode xmlNode1 =28              xmlNode1.ChildNodes)
29 30                 string temp = node.InnerText;
31 32 33             34 35 
36          Image cnValidateByteResponse(XmlDocument xmlDoc) {
37 
38             XmlNamespaceManager nsmgr = 39             nsmgr.AddNamespace(40             nsmgr.AddNamespace(41             nsmgr.AddNamespace(42             List<43             XmlNode xmlNode = xmlDoc.SelectSingleNode(44             XmlNode xmlNode1 =string baseCode = xmlNode1.FirstChild.InnerText;
byte[] buffer = Convert.FromBase64String(baseCode);
47             MemoryStream mm =  MemoryStream(buffer);
48             Image image = Image.FromStream(mm);
49              image;
51     }
View Code

 1    2          通过二进制转换图片
 3          4         <param name="sender"></param>
 5         <param name="e"></param>
 6         void btnValidateByte_Click(object sender,EventArgs e)
 8             string methodName = cnValidateByte 9             string url = System.Configuration.ConfigurationManager.AppSettings[validateurl].ToString();
10             string xmlPath = AppDomain.CurrentDomain.BaseDirectory + CfgFileRequestByte.xml11            
12             Hashtable pars = new Hashtable();用来存放参数
13             pars[web:byString"] = 贺祥ABC14             XmlDocument xmlDoc = WebSvcCaller.QuerySoapWebService(url,methodName,pars,1)">15             Image img = XmlHelper.cnValidateByteResponse(xmlDoc);
this.pbOne.Image =17             this.pbOne.Width = img.Width;
18             this.pbOne.Height = img.Height;
19 20 
 直接获取图片
25         26         void btnValidateImage_Click(27 cnValidateImage29             30             CfgFileRequestImage.xml31 
32             Hashtable pars = 33             pars[34             Image img = WebSvcCaller.QuerySoapWebService2(url,1)">35           
36             37             38             39         }
View Code

---------------------------------------------------------------------------------------------------------------

关于源码下载,请点击下面的链接即可:

?源码下载

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读