C# 天气预报
本文通过一个完整的实例,讲解如何通过访问中国天气网提供的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 using System; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 using 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 [Serializable] 22 public class CWeatherInfo 23 { 24 [JsonProperty("city")] 25 public string City { get; set; } 26 27 [JsonProperty("cityid")] 28 public string CityId { get; set; } 29 30 /// <summary> 31 /// 气温1 32 /// </summary> 33 [JsonProperty("temp1")] 34 public string Temp1 { get; set; } 35 36 /// <summary> 37 /// 气温2 38 /// </summary> 39 [JsonProperty("temp2")] 40 public string Temp2 { get; set; } 41 42 /// <summary> 43 /// 天气情况 44 /// </summary> 45 [JsonProperty("weather")] 46 public string Weather { get; set; } 47 48 [JsonProperty("img1")] 49 public string Img1 { get; set; } 50 51 [JsonProperty("img2")] 52 public string Img2 { get; set; } 53 54 /// <summary> 55 /// 更新时间 56 /// </summary> 57 [JsonProperty("ptime")] 58 public string PTime { get; set; } 59 60 } 61 62 /// <summary> 63 /// 城市基础天气信息类(另外一个) 64 /// </summary> 65 [Serializable] 66 public class DWeather 67 { 68 [JsonProperty("weatherinfo")] 69 public DWeatherInfo WeatherInfo { get; set; } 70 } 71 72 [Serializable] 73 public class DWeatherInfo { 74 [JsonProperty("city")] 75 public string City { get; set; } 76 77 [JsonProperty("cityid")] 78 public string CityId { get; set; } 79 80 /// <summary> 81 /// 气温1 82 /// </summary> 83 [JsonProperty("temp")] 84 public string Temp { get; set; } 85 86 /// <summary> 87 /// 风向 88 /// </summary> 89 [JsonProperty("WD")] 90 public string WD { get; set; } 91 92 /// <summary> 93 /// 风速 94 /// </summary> 95 [JsonProperty("WS")] 96 public string WS { get; set; } 97 98 /// <summary> 99 /// 相对湿度 100 /// </summary> 101 [JsonProperty("SD")] 102 public string SD { get; set; } 103 104 /// <summary> 105 /// 风力 106 /// </summary> 107 [JsonProperty("WSE")] 108 public string WSE { get; set; } 109 110 /// <summary> 111 /// 更新时间 112 /// </summary> 113 [JsonProperty("time")] 114 public string Time { get; set; } 115 116 /// <summary> 117 /// 是否有雷达图(1表示有雷达图) 118 /// </summary> 119 [JsonProperty("isRadar")] 120 public string IsRadar { get; set; } 121 122 /// <summary> 123 /// 雷达图地址(AZ9532为青岛雷达) 124 /// </summary> 125 [JsonProperty("Radar")] 126 public string Radar { get; set; } 127 128 /// <summary> 129 /// 130 /// </summary> 131 [JsonProperty("njd")] 132 public string Njd { get; set; } 133 134 [JsonProperty("qy")] 135 public string Qy { get; set; } 136 137 [JsonProperty("rain")] 138 public string Rain { get; set; } 139 140 } 141 142 /// <summary> 143 /// 新浪天气预报API实体类 144 /// </summary> 145 [Serializable] 146 [XmlRoot("Profiles")] 147 public class SWeather { 148 149 [JsonProperty("Weather")] 150 [XmlElementAttribute("Weather")] 151 public SWeatherInfo WeatherInfo { get; set; } 152 } 153 154 public class SWeatherInfo { 155 156 /// <summary> 157 /// 对应的查询城市 158 /// </summary> 159 [JsonProperty("city")] 160 [XmlElementAttribute("city")] 161 public string City { get; set; } 162 163 /// <summary> 164 /// 白天天气情况 165 /// </summary> 166 [JsonProperty("status1")] 167 [XmlElementAttribute("status1")] 168 public string Status1 { get; set; } 169 170 /// <summary> 171 /// 夜间天气情况 172 /// </summary> 173 [JsonProperty("status2")] 174 [XmlElementAttribute("status2")] 175 public string Status2 { get; set; } 176 177 /// <summary> 178 /// 白天天气情况拼音 179 /// </summary> 180 [JsonProperty("figure1")] 181 [XmlElementAttribute("figure1")] 182 public string Figure1 { get; set; } 183 184 /// <summary> 185 /// 夜间天气情况拼音 186 /// </summary> 187 [JsonProperty("figure2")] 188 [XmlElementAttribute("figure2")] 189 public string Figure2 { get; set; } 190 191 /// <summary> 192 /// 白天风向 193 /// </summary> 194 [JsonProperty("direction1")] 195 [XmlElementAttribute("direction1")] 196 public string Direction1 { get; set; } 197 198 /// <summary> 199 /// 夜晚风向 200 /// </summary> 201 [JsonProperty("direction2")] 202 [XmlElementAttribute("direction2")] 203 public string Direction2 { get; set; } 204 205 /// <summary> 206 /// 白天风力 207 /// </summary> 208 [JsonProperty("power1")] 209 [XmlElementAttribute("power1")] 210 public string Power1 { get; set; } 211 212 /// <summary> 213 /// 夜间风力 214 /// </summary> 215 [JsonProperty("power2")] 216 [XmlElementAttribute("power2")] 217 public string Power2 { get; set; } 218 219 /// <summary> 220 /// 白天温度 221 /// </summary> 222 [JsonProperty("temperature1")] 223 [XmlElementAttribute("temperature1")] 224 public string Temperature1 { get; set; } 225 226 /// <summary> 227 /// 夜间温度 228 /// </summary> 229 [JsonProperty("temperature2")] 230 [XmlElementAttribute("temperature2")] 231 public string Temperature2 { get; set; } 232 233 /// <summary> 234 /// 体感指数 235 /// </summary> 236 [JsonProperty("ssd")] 237 [XmlElementAttribute("ssd")] 238 public string Ssd { get; set; } 239 240 /// <summary> 241 /// 白天体感温度 242 /// </summary> 243 [JsonProperty("tgd1")] 244 [XmlElementAttribute("tgd1")] 245 public string Tgd1 { get; set; } 246 247 /// <summary> 248 /// 夜间体感温度 249 /// </summary> 250 [JsonProperty("tgd2")] 251 [XmlElementAttribute("tgd2")] 252 public string Tgd2 { get; set; } 253 254 /// <summary> 255 /// 紫外线强度 256 /// </summary> 257 [JsonProperty("zwx")] 258 [XmlElementAttribute("zwx")] 259 public string Zwx { get; set; } 260 261 /// <summary> 262 /// 空调指数 263 /// </summary> 264 [JsonProperty("ktk")] 265 [XmlElementAttribute("ktk")] 266 public string Ktk { get; set; } 267 268 /// <summary> 269 /// 污染指数 270 /// </summary> 271 [JsonProperty("pollution")] 272 [XmlElementAttribute("pollution")] 273 public string Pollution { get; set; } 274 275 /// <summary> 276 /// 洗车指数 277 /// </summary> 278 [JsonProperty("xcz")] 279 [XmlElementAttribute("xcz")] 280 public string Xcz { get; set; } 281 282 /// <summary> 283 /// 综合指数这个我不确定 284 /// </summary> 285 [JsonProperty("zho")] 286 [XmlElementAttribute("zho")] 287 public string Zho { get; set; } 288 289 /// <summary> 290 /// 没猜出来是什么指数,没有数值 291 /// </summary> 292 [JsonProperty("diy")] 293 [XmlElementAttribute("diy")] 294 public string Diy { get; set; } 295 296 /// <summary> 297 /// 同上 298 /// </summary> 299 [JsonProperty("fas")] 300 [XmlElementAttribute("fas")] 301 public string Fas { get; set; } 302 303 /// <summary> 304 /// 穿衣指数 305 /// </summary> 306 [JsonProperty("chy")] 307 [XmlElementAttribute("chy")] 308 public string Chy { get; set; } 309 310 /// <summary> 311 /// zho的说明,然而zho是什么指数我也不确定 312 /// </summary> 313 [JsonProperty("zho_shuoming")] 314 [XmlElementAttribute("zho_shuoming")] 315 public string Zho_shuoming { get; set; } 316 317 /// <summary> 318 /// 同上 319 /// </summary> 320 [JsonProperty("diy_shuoming")] 321 [XmlElementAttribute("diy_shuoming")] 322 public string Diy_shuoming { get; set; } 323 324 /// <summary> 325 /// 同上 326 /// </summary> 327 [JsonProperty("fas_shuoming")] 328 [XmlElementAttribute("fas_shuoming")] 329 public string Fas_shuoming { get; set; } 330 331 /// <summary> 332 /// 穿衣指数说明 333 /// </summary> 334 [JsonProperty("chy_shuoming")] 335 [XmlElementAttribute("chy_shuoming")] 336 public string Chy_shuoming { get; set; } 337 338 /// <summary> 339 /// 污染程度 340 /// </summary> 341 [JsonProperty("pollution_l")] 342 [XmlElementAttribute("pollution_l")] 343 public string Pollution_l { get; set; } 344 345 /// <summary> 346 /// 紫外线指数概述 347 /// </summary> 348 [JsonProperty("zwx_l")] 349 [XmlElementAttribute("zwx_l")] 350 public string Zwx_l { get; set; } 351 352 /// <summary> 353 /// 体感指数概述 354 /// </summary> 355 [JsonProperty("ssd_l")] 356 [XmlElementAttribute("ssd_l")] 357 public string Ssd_l { get; set; } 358 359 /// <summary> 360 /// 这个不知道 361 /// </summary> 362 [JsonProperty("fas_l")] 363 [XmlElementAttribute("fas_l")] 364 public string Fas_l { get; set; } 365 366 /// <summary> 367 /// 这个不知道 368 /// </summary> 369 [JsonProperty("zho_l")] 370 [XmlElementAttribute("zho_l")] 371 public string Zho_l { get; set; } 372 373 /// <summary> 374 /// 穿衣指数概述(可理解为穿衣建议) 375 /// </summary> 376 [JsonProperty("chy_l")] 377 [XmlElementAttribute("chy_l")] 378 public string Chy_l { get; set; } 379 380 /// <summary> 381 /// 空调指数概述 382 /// </summary> 383 [JsonProperty("ktk_l")] 384 [XmlElementAttribute("ktk_l")] 385 public string Ktk_l { get; set; } 386 387 /// <summary> 388 /// 洗车指数概述 389 /// </summary> 390 [JsonProperty("xcz_l")] 391 [XmlElementAttribute("xcz_l")] 392 public string Xcz_l { get; set; } 393 394 /// <summary> 395 /// 这个不知道 396 /// </summary> 397 [JsonProperty("diy_l")] 398 [XmlElementAttribute("diy_l")] 399 public string Diy_l { get; set; } 400 401 /// <summary> 402 /// 污染指数详细说明 403 /// </summary> 404 [JsonProperty("pollution_s")] 405 [XmlElementAttribute("pollution_s")] 406 public string Pollution_s { get; set; } 407 408 /// <summary> 409 /// 紫外线详细说明 410 /// </summary> 411 [JsonProperty("zwx_s")] 412 [XmlElementAttribute("zwx_s")] 413 public string Zwx_s { get; set; } 414 415 /// <summary> 416 /// 体感详细说明 417 /// </summary> 418 [JsonProperty("ssd_s")] 419 [XmlElementAttribute("ssd_s")] 420 public string Ssd_s { get; set; } 421 422 /// <summary> 423 /// 空调指数详细说明 424 /// </summary> 425 [JsonProperty("ktk_s")] 426 [XmlElementAttribute("ktk_s")] 427 public string Ktk_s { get; set; } 428 429 /// <summary> 430 /// 洗车详细说明 431 /// </summary> 432 [JsonProperty("xcz_s")] 433 [XmlElementAttribute("xcz_s")] 434 public string Xcz_s { get; set; } 435 436 /// <summary> 437 /// 感冒指数 438 /// </summary> 439 [JsonProperty("gm")] 440 [XmlElementAttribute("gm")] 441 public string Gm { get; set; } 442 443 /// <summary> 444 /// 感冒指数概述 445 /// </summary> 446 [JsonProperty("gm_l")] 447 [XmlElementAttribute("gm_l")] 448 public string Gm_l { get; set; } 449 450 /// <summary> 451 /// 感冒指数详细说明 452 /// </summary> 453 [JsonProperty("gm_s")] 454 [XmlElementAttribute("gm_s")] 455 public string Gm_s { get; set; } 456 457 /// <summary> 458 /// 运动指数 459 /// </summary> 460 [JsonProperty("yd")] 461 [XmlElementAttribute("yd")] 462 public string Yd { get; set; } 463 464 /// <summary> 465 /// 运动指数概述 466 /// </summary> 467 [JsonProperty("yd_l")] 468 [XmlElementAttribute("yd_l")] 469 public string Yd_l { get; set; } 470 471 /// <summary> 472 /// 运动指数详细说明 473 /// </summary> 474 [JsonProperty("yd_s")] 475 [XmlElementAttribute("yd_s")] 476 public string Yd_s { get; set; } 477 478 /// <summary> 479 /// 天气数据日期 480 /// </summary> 481 [JsonProperty("savedate_weather")] 482 [XmlElementAttribute("savedate_weather")] 483 public string Savedate_weather { get; set; } 484 485 /// <summary> 486 /// 生活数据日期 487 /// </summary> 488 [JsonProperty("savedate_life")] 489 [XmlElementAttribute("savedate_life")] 490 public string Savedate_life { get; set; } 491 492 /// <summary> 493 /// 指数数据日期 494 /// </summary> 495 [JsonProperty("savedate_zhishu")] 496 [XmlElementAttribute("savedate_zhishu")] 497 public string Savedate_zhishu { get; set; } 498 499 /// <summary> 500 /// 更新时间 501 /// </summary> 502 [JsonProperty("udatetime")] 503 [XmlElementAttribute("udatetime")] 504 public string Udatetime { get; set; } 505 506 } 507 }
国家代码,对应级联菜单的实体类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace DemoWeather 8 { 9 /// <summary> 10 /// 国家类 11 /// </summary> 12 public class Country { 13 14 /// <summary> 15 /// id 16 /// </summary> 17 public string Id { get; set; } 18 19 /// <summary> 20 /// 国家名 21 /// </summary> 22 public string Name { get; set; } 23 /// <summary> 24 /// 省份列表 25 /// </summary> 26 public List<Province> ProvinceList { get; set; } 27 28 public override string ToString() 29 { 30 return this.Name; 31 } 32 } 33 34 /// <summary> 35 /// 省份类 36 /// </summary> 37 public class Province 38 { 39 /// <summary> 40 /// 省份名称 41 /// </summary> 42 public string Name { get; set; } 43 44 /// <summary> 45 /// 省份ID 46 /// </summary> 47 public string Id { get; set; } 48 49 /// <summary> 50 /// 城市列表 51 /// </summary> 52 public List<City> CityList { get; set; } 53 54 public override string ToString() 55 { 56 return this.Name; 57 } 58 } 59 60 /// <summary> 61 /// 城市类 62 /// </summary> 63 public class City { 64 65 /// <summary> 66 /// 城市名称 67 /// </summary> 68 public string Name { get; set; } 69 70 /// <summary> 71 /// 城市Id 72 /// </summary> 73 public string Id { get; set; } 74 75 /// <summary> 76 /// 城市里面的城区列表 77 /// </summary> 78 public List<Urban> UrbanList { get; set; } 79 80 public override string ToString() 81 { 82 return this.Name; 83 } 84 } 85 86 /// <summary> 87 /// 城区,县城 88 /// </summary> 89 public class Urban { 90 91 /// <summary> 92 /// 城区名称 93 /// </summary> 94 public string Name { get; set; } 95 96 /// <summary> 97 /// 城区ID 98 /// </summary> 99 public string Id { get; set; } 100 101 public override string ToString() 102 { 103 return this.Name; 104 } 105 } 106 }
访问接口类代码如下:
1 using Newtonsoft.Json; 2 using System; 3 using System.Collections.Generic; 4 using System.IO; 5 using System.Linq; 6 using System.Net; 7 using System.Text; 8 using System.Threading; 9 using System.Threading.Tasks; 10 using System.Xml.Serialization; 11 12 namespace DemoWeather 13 { 14 /// <summary> 15 /// 访问天气API接口 16 /// </summary> 17 public class WeatherAccess 18 { 19 /// <summary> 20 /// 获取天气站点的信息 21 /// </summary> 22 /// <typeparam name="T">返回类的信息</typeparam> 23 /// <param name="url"><网址/param> 24 /// <returns></returns> 25 public static T CallWeatherWebSite<T>(string url) 26 { 27 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 28 request.Method = "GET"; 29 request.Accept = "text/json"; 30 HttpWebResponse response = request.GetResponse() as HttpWebResponse; 31 string strJson = string.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 break; 42 } 43 Thread.Sleep(1000); 44 } 45 //反序列化信息 46 if (!string.IsNullOrEmpty(strJson)) 47 { 48 T t = JsonConvert.DeserializeObject<T>(strJson); 49 return t; 50 } 51 return default(T); 52 } 53 54 public static T CallWeatherWebSite2<T>(string url) 55 { 56 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 57 request.Method = "GET"; 58 request.Accept = "text/xml"; 59 HttpWebResponse response = request.GetResponse() as HttpWebResponse; 60 string strXml = string.Empty; 61 bool flag = false; 62 63 while (true) 64 { 65 if (response.StatusCode == HttpStatusCode.OK) 66 { 67 Stream stream = response.GetResponseStream(); 68 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) 69 { 70 strXml = reader.ReadToEnd(); 71 } 72 break; 73 } 74 Thread.Sleep(1000); 75 } 76 //反序列化信息 77 if (!string.IsNullOrEmpty(strXml)) 78 { 79 T t = new XmlHelper<T>().Deserialize2(strXml); 80 return t; 81 } 82 return default(T); 83 } 84 } 85 }
新浪网天气如下图所示【数据是实时更新】:
备注:
【上面中国天气网接口读取的数据,总感觉有些不对,不知道是不是没有更新还是咋样,权当练习了】
API接口中101110101是城市的代码,如果要查询其他城市的天气,只需要修改城市的代码即可。关于城市代码,已经整理成配置文件xml,然后通过级联菜单的方式进行加载。
-------------------------------调用webservice接口,生成验证码-------------------------------
接口网址:http://www.webxml.com.cn/WebServices/ValidateCodeWebService.asmx?wsdl
1 public class WebSvcCaller 2 { 3 4 private static Hashtable hshtableXML = new Hashtable(); 5 6 7 /// <summary> 8 /// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值 9 /// </summary> 10 public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string xmlPath) 11 { 12 HttpWebRequest request = null; 13 XmlDocument doc = new 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 = false; 23 request.Timeout = 10000; 24 byte[] data = EncodeParsToSoap(Pars, MethodName, xmlPath); 25 WriteRequestData(request, data);//将处理成字节组的XML写到流中发送到服务端 26 27 doc = ReadXmlResponse(request.GetResponse());//读取服务端返回的结果 28 29 } 30 catch (Exception ex) 31 { 32 33 } 34 finally { 35 if (request != null){ 36 request.Abort(); 37 } 38 } 39 return doc; 40 } 41 42 public static Image QuerySoapWebService2(String URL, String MethodName, Hashtable Pars, string xmlPath) 43 { 44 HttpWebRequest request = null; 45 Image doc = null; 46 try 47 { 48 request = (HttpWebRequest)HttpWebRequest.Create(URL); 49 request.Method = "POST"; 50 request.Accept = @"gzip,deflate"; 51 request.ContentType = @"text/xml;charset=utf-8"; 52 request.UserAgent = @"Jakarta Commons-HttpClient/3.1"; 53 request.Credentials = CredentialCache.DefaultCredentials; 54 request.KeepAlive = false; 55 request.Timeout = 10000; 56 byte[] data = EncodeParsToSoap(Pars, MethodName, xmlPath); 57 WriteRequestData(request, data);//将处理成字节组的XML写到流中发送到服务端 58 59 doc = ReadImageResponse(request.GetResponse());//读取服务端返回的结果 60 61 } 62 catch (Exception ex) 63 { 64 65 } 66 finally 67 { 68 if (request != null) 69 { 70 request.Abort(); 71 } 72 } 73 return doc; 74 } 75 76 /// <summary> 77 /// 处理要发送的XML文档 78 /// </summary> 79 /// <param name="Pars">参数</param> 80 /// <param name="MethodName">方法名</param> 81 private static byte[] EncodeParsToSoap(Hashtable Pars, String MethodName,string xmlPath) 82 { 83 XmlDocument xml = null; 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 = new XmlDocument(); 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) 102 { 103 XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable); 104 nsmgr.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/"); 105 nsmgr.AddNamespace("web", "http://WebXml.com.cn/"); 106 Hashtable subpars = de.Value as Hashtable; 107 if (subpars == null) 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 else 114 { 115 foreach (DictionaryEntry subde in subpars) 116 { 117 string subNode = "soapenv:Envelope/soapenv:Body/web:" + MethodName + "/" + de.Key.ToString() + "/" + subde.Key.ToString(); 118 XmlNode node = xml.SelectSingleNode(subNode, nsmgr); 119 node.InnerText = subde.Value.ToString(); 120 } 121 } 122 123 } 124 } 125 //将修改后的XML文件保存到流中 126 //这样做还可以保证发送的XML文件也是格式化的那种形式,而不是一整行 127 //如通过OuterXml获取的就是一整行,这样也可能会导致服务端解析失败,个人这次就碰到这种情况了 128 MemoryStream outStream = new 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 return buffer; 140 } 141 142 143 /// <summary> 144 /// 写到流中,发送给服务端 145 /// </summary> 146 /// <param name="request">HttpWebRequest连接对象</param> 147 /// <param name="data">要写入连接流发给服务端的内容</param> 148 private static void WriteRequestData(HttpWebRequest request, byte[] data) 149 { 150 request.ContentLength = data.Length; 151 Stream writer = request.GetRequestStream(); 152 writer.Write(data, 0, data.Length); 153 writer.Close(); 154 } 155 156 /// <summary> 157 /// 读取服务端返回的结果 158 /// </summary> 159 private static XmlDocument ReadXmlResponse(WebResponse response) 160 { 161 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 162 String retXml = sr.ReadToEnd(); 163 sr.Close(); 164 XmlDocument doc = new XmlDocument(); 165 doc.LoadXml(retXml); 166 return doc; 167 } 168 169 private static Image ReadImageResponse(WebResponse response) 170 { 171 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 172 //String retXml = sr.ReadToEnd(); 173 Stream stream = sr.BaseStream; 174 175 176 Image img = Image.FromStream(stream); 177 sr.Close(); 178 return img; 179 } 180 }
1 public class XmlHelper 2 { 3 public static List<string> getSupportProvinceResponse(XmlDocument xmlDoc) 4 { 5 XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); 6 nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); 7 nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); 8 nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); 9 List<string> lstTemp = new List<string>(); 10 XmlNode xmlNode = xmlDoc.SelectSingleNode("soap:Envelope/soap:Body", nsmgr); 11 XmlNode xmlNode1 = xmlNode.FirstChild.FirstChild; 12 foreach (XmlNode node in xmlNode1.ChildNodes) { 13 string temp= node.InnerText; 14 lstTemp.Add(temp); 15 } 16 return lstTemp; 17 } 18 19 public static List<string> getSupportCityResponse(XmlDocument xmlDoc) 20 { 21 XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); 22 nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); 23 nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); 24 nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); 25 List<string> lstTemp = new List<string>(); 26 XmlNode xmlNode = xmlDoc.SelectSingleNode("soap:Envelope/soap:Body", nsmgr); 27 XmlNode xmlNode1 = xmlNode.FirstChild.FirstChild; 28 foreach (XmlNode node in xmlNode1.ChildNodes) 29 { 30 string temp = node.InnerText; 31 lstTemp.Add(temp); 32 } 33 return lstTemp; 34 } 35 36 public static Image cnValidateByteResponse(XmlDocument xmlDoc) { 37 38 XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); 39 nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); 40 nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); 41 nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); 42 List<string> lstTemp = new List<string>(); 43 XmlNode xmlNode = xmlDoc.SelectSingleNode("soap:Envelope/soap:Body", nsmgr); 44 XmlNode xmlNode1 = xmlNode.FirstChild.FirstChild; 45 string baseCode = xmlNode1.FirstChild.InnerText; 46 byte[] buffer = Convert.FromBase64String(baseCode); 47 MemoryStream mm = new MemoryStream(buffer); 48 Image image = Image.FromStream(mm); 49 return image; 50 } 51 }
1 /// <summary> 2 /// 通过二进制转换图片 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void btnValidateByte_Click(object sender, EventArgs e) 7 { 8 string methodName = "cnValidateByte"; 9 string url = System.Configuration.ConfigurationManager.AppSettings["validateurl"].ToString(); 10 string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"CfgFile\RequestByte.xml"; 11 12 Hashtable pars = new Hashtable();//用来存放参数 13 pars["web:byString"] = "贺祥ABC"; 14 XmlDocument xmlDoc = WebSvcCaller.QuerySoapWebService(url, methodName, pars, xmlPath); 15 Image img = XmlHelper.cnValidateByteResponse(xmlDoc); 16 this.pbOne.Image = img; 17 this.pbOne.Width = img.Width; 18 this.pbOne.Height = img.Height; 19 } 20 21 /// <summary> 22 /// 直接获取图片 23 /// </summary> 24 /// <param name="sender"></param> 25 /// <param name="e"></param> 26 private void btnValidateImage_Click(object sender, EventArgs e) 27 { 28 string methodName = "cnValidateImage"; 29 string url = System.Configuration.ConfigurationManager.AppSettings["validateurl"].ToString(); 30 string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"CfgFile\RequestImage.xml"; 31 32 Hashtable pars = new Hashtable();//用来存放参数 33 pars["web:byString"] = "贺祥ABC"; 34 Image img = WebSvcCaller.QuerySoapWebService2(url, methodName, pars, xmlPath); 35 36 this.pbOne.Image = img; 37 this.pbOne.Width = img.Width; 38 this.pbOne.Height = img.Height; 39 }
---------------------------------------------------------------------------------------------------------------
关于源码下载,请点击下面的链接即可:
作者:老码识途
出处:http://www.cnblogs.com/hsiang/
本文版权归作者和博客园共有,写文不易,支持原创,欢迎转载【点赞】,转载请保留此段声明,且在文章页面明显位置给出原文连接,谢谢。
关注个人公众号,定时同步更新技术及职场文章