使用天气预报api(中国天气网)获取城市天气(1)---async/await 异步编程

中国天气weather.com
http://m.weather.com.cn/data/101110101.html(六天预报)


http://www.weather.com.cn/data/sk/101110101.html(实时天气信息)


其中101110101是城市的代码,获得城市代码进入


http://www.weather.com.cn
在搜索框上输入你要需要获得天气的城市,点击查询,即可在地址栏获得相应城市编号,然后替换

http://m.weather.com.cn/data/101110101.html


这里使用第二个接口获取实时天气信息,获取到json的数据,格式如下:

{"weatherinfo":{"city":"西安","cityid":"101110101","temp":"34","WD":"东北风","WS":"3级","SD":"34%","WSE":"3","time":"14:00","isRadar":"1","Radar":"JC_RADAR_AZ9290_JB"}}


首先新建CityInfo类用作记录城市天气信息及json的反序列化。

   class CityInfo
    {
        public string city { get; set; }
        public string cityid { get;  set; }

        public string temp { get;  set; }
        public string WD { get;  set; }
        public string SD { get;  set; }
        public string WSE { get;  set; }
        public string time { get;  set; }
        public string isRadar { get;  set; }

        public string Radar { get;  set; }

    



       

        private  CityInfo()        //这个对象不能被外部创建
        {
        }

        public override string ToString()
        {
            return string.Format("city:{0}\ncityid:{1}\ntemp:{2}\nWD:{3}\nSD:{4}\nWSE:{5}\ntime:{6}\nisRadar:{7}\nRadar:{8}",
                city, cityid, temp, WD, SD, WSE, time, isRadar, Radar);
        }

         
         
         
         //将txt文件的城市列表写到xml文件中
         public static void changeTxtToXml(string srcPath,string distPath){
             StreamReader src=new StreamReader(srcPath);
             StreamWriter dist = new StreamWriter(distPath);

             dist.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?> " );//写入xml头
             dist.WriteLine("<citys>");
             string line;  //每一行数据
             while ((line = src.ReadLine()) != null)
             {
                 line = line.Trim();
                 if (!line.Equals("") && !line[0].Equals('#')) //#开头为注释,且该行不为空;
                 {
                     var items= line.Split('=');
                     dist.WriteLine("<city>");
                     dist.WriteLine("<id>"+items[0]+"</id>");
                     dist.WriteLine("<name>" + items[1] + "</name>");
                     dist.WriteLine("</city>");
                 }
             }

             dist.WriteLine("</citys>");

             src.Close();
             dist.Flush();
             dist.Close();



         }

         
        static HttpClient httpClient = new HttpClient();


         //提供用id号获取天气信息方法
        public  static async Task<CityInfo>  getCityInfoByIdAsync(string id)
        {
            var requestUri=string.Format("http://www.weather.com.cn/data/sk/{0}.html",id);

            var cityinfo =await httpClient.GetStringAsync(requestUri).ContinueWith<Task<CityInfo>>(
                async json =>
                {
                    string jsonString = await json;
                    jsonString = jsonString.Substring(15, jsonString.Length - 16);                
                    

                    return JsonConvert.DeserializeObject<CityInfo>(jsonString);
                }
                
                
                );        
             

            return await cityinfo;
                    
        }

        //提供用城市名获取天气信息方法
        public static async Task<CityInfo> getCityInfoByNameAsync(string cityName)
        {
            //从xml获取id号;
            string path = "c:\\users\\mr\\documents\\visual studio 2013\\Projects\\WeatherForcast\\WeatherForcast\\Data\\cityList.xml";
            XElement xe = XElement.Load(path);
            var id = from a in xe.Elements("city")
                     where a.Element("name").Value.Equals(cityName)
                     select a.Element("id").Value;
            string cityid = id.ElementAt(0);
            return await getCityInfoByIdAsync(cityid);

        }
}
CityInfo类构造函数为私有,不能直接初始化,只能通过两个静态方法创建:
public static async Task<CityInfo> getCityInfoByNameAsync(string cityName);
<pre name="code" class="csharp" style="font-size: 14px;">public  static async Task<CityInfo>  getCityInfoByIdAsync(string id);

 主函数: 
 

static  void Main(string[] args)
        {
            
            while (true)
            {
                Console.WriteLine("********************************************************");
                Console.WriteLine("请输入城市名称:");
                string input = Console.ReadLine();          
               

                Task<CityInfo> a = CityInfo.getCityInfoByNameAsync(input);
                Console.Write("正在查询,请骚等.");
                while (a.IsCompleted != true)
                {                
                 
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                   
                  
                   
                }
                
                Console.WriteLine();
                Console.WriteLine(a.Result.ToString());

            }
          
          
        }
主函数调用 getCityInfoByNameAsync获取城市的天气信息。使用异步async,使用轮询方式查询结果。最后输出查询的结果。



参考:http://www.cnblogs.com/danyueweb/p/3521973.html,

     http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx#BKMK_Threads

      http://www.cnblogs.com/TianFang/archive/2013/01/03/2842913.html

     http://msdn.microsoft.com/zh-cn/library/ms228975(v=vs.110).aspx


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值