C#获取中国免费的天气信息

一、获取中国免费的天气信息有两种方式

注意:本篇文章的项目工程下载连接为:TestWeather

1.1、获取中国免费的天气信息方式1

1.1.1、方式1获取中国免费的天气信息流程为:

①获取省级直辖市列表-->选择对应省级直辖市列表中的一个获取到对应的编号;

②根据选择的该省级直辖市名称获取的编号获取对应的城市列表-->选择该省级直辖市下城市列表中的一个获取对应的编号;

③根据选择的该省级直辖市下的城市名称获取的编号获取对应的地州列表-->选择该省级直辖市下城市列表中的一个获取对应的编号

1.1.2、中国气象局开放的获取天气数据的webApi接口如下

①获取中国省级直辖市列表的接口:http://www.weather.com.cn/data/city3jdata/china.html

②获取中国省级直辖市下城市列表的接口:http://www.weather.com.cn/data/city3jdata/provshi/10129.html【该加粗的10129就是需要查询的省级直辖市名称的编号,10129是云南的编号】

③获取中国省级直辖市下城市下地州列表的接口:http://www.weather.com.cn/data/city3jdata/station/1012901.html 【该加粗的1012901就是需要查询的省级直辖市下城市名称的编号,1012901是云南昆明的编号;而101290108是云南昆明呈贡的编号】

④根据获取的中国省级直辖市下城市下地州的编号得到天气数据接口:接口1:http://www.weather.com.cn/data/cityinfo/101290108.html 接口2:http://www.weather.com.cn/data/sk/101290108.html 接口3:https://api.help.bj.cn/apis/weather/?id=101290108【该加粗的101290108就是目前需要查询的地州的天气情况所需的编号】

【注意接口3不是中国天气接口,是一个第三方免费接口,该接口的网址为:第三方免费天气接口

 

1.1.3、获取天气的项目程序如下:

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Collections;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Text.RegularExpressions;

    class Program
    {
        static void Main(string[] args)
        {
            //获取天气信息
            GetWeatherInfos();

        }

        //获取天气信息
        private static void GetWeatherInfos()
        {
          
            try
            {
                //1-获取到当前中国的所有省份直辖市信息列表
                Console.WriteLine("省及直辖市:");
                Hashtable HTProvice = GetInfoAndPrint("http://www.weather.com.cn/data/city3jdata/china.html");
                //2-输入当前需要查询的省份直辖市名称
                string Provice =null;
                while (true)
                {
                    Console.Write("请输入需要查询的省或直辖市:");
                    Provice = Console.ReadLine();

                    Provice = IsSameInfo(Provice, HTProvice);
                    if (!string.IsNullOrEmpty(Provice)) break;
                }

                //3-根据当前输入需要查询的省份直辖市名称获取到该省份直辖市包含的城市
                Hashtable HTCity = GetInfoAndPrint($"http://www.weather.com.cn/data/city3jdata/provshi/{Provice}.html");
                Console.WriteLine("城市:");
                //4-输入当前需要查询的城市名称
                string City =null;
                while (true)
                {
                    Console.Write("请输入需要查询的城市:");
                    City = Console.ReadLine();
                    City = IsSameInfo(City, HTCity);
                    if (!string.IsNullOrEmpty(City)) break;
                }

                //5-根据当前输入当前需要查询的城市名称获取到该城市包含的地州信息
                Hashtable HTArea = GetInfoAndPrint($"http://www.weather.com.cn/data/city3jdata/station/{Provice}{City}.html");
                Console.WriteLine("地州:");
               
                //6-输入当前需要查询的地州名称
                string Area=null;
                string strAreaName = null;
                while (true)
                {
                    Console.Write("请输入需要查询的地州:");
                    Area = Console.ReadLine();
                    strAreaName = Area;
                    Area = IsSameInfo(Area, HTArea);
                    if (!string.IsNullOrEmpty(Area)) break;
                }

                //7-获取到当前需要查询的地州对应的总编号
                string StrAreaNumber = string.Format("{0}{1}{2}",Provice, City, Area);

                Console.WriteLine("当前查询的省市地州为:"+ StrAreaNumber);


                //免费的天气信息获取API
                string WeatherInfos = HttpGet($"https://api.help.bj.cn/apis/weather/?id={StrAreaNumber}");
                Console.WriteLine("天气信息:");
                JObject jot = AnalayJson.AnalayJsonStringToJObject(WeatherInfos);
                Console.WriteLine("1-反馈代码:"+jot["status"].ToString());
                Console.WriteLine("2-实时温度:" + jot["temp"].ToString() + "℃");
                Console.WriteLine("3-风    向:" + jot["wd"].ToString());
                Console.WriteLine("4-风    力:" + jot["wdforce"].ToString());
                Console.WriteLine("5-风    速:" + jot["wdspd"].ToString());
                Console.WriteLine("6-更新时间:" + jot["uptime"].ToString());
                Console.WriteLine("7-天气状况:" + jot["weather"].ToString());
                Console.WriteLine("8-天气图标:" + jot["weatherimg"].ToString());
                Console.WriteLine("9-气    压:" + jot["stp"].ToString() + "pa");
                Console.WriteLine("10- 能见度:" + jot["wisib"].ToString());
                Console.WriteLine("11-湿   度:" + jot["humidity"].ToString());
                Console.WriteLine("12-24小时降雨量:" + jot["prcp24h"].ToString());
                Console.WriteLine("13-PM2.5  :" + jot["pm25"].ToString());
                Console.WriteLine("14-今日日期:" + jot["today"].ToString());


                Console.WriteLine("-----------免费的天气信息获取完成----------------");


            Console.WriteLine("按任何键退出...");
            Console.ReadKey();
        }

        /// <summary>
        /// 发送GET请求
        /// </summary>
        /// <param name="url">请求URL,如果需要传参,在URL末尾加上“?+参数名=参数值”即可</param>
        /// <returns>返回对应的相应信息</returns>
        private static string HttpGet(string url)
        {
            if (!string.IsNullOrEmpty(url))
            {
                try
                {
                    //创建
                    HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                    //设置请求方法
                    httpWebRequest.Method = "GET";
                    //请求超时时间
                    httpWebRequest.Timeout = 20000;
                    //发送请求
                    HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    //利用Stream流读取返回数据
                    StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
                    //获得最终数据,一般是json
                    string responseContent = streamReader.ReadToEnd();
                    streamReader.Close();
                    httpWebResponse.Close();
                    return responseContent;
                }
                catch (Exception ex)
                {

                    throw new Exception("获取当前 "+url+" 信息出错,请检查!!!"+ex.Message);
                }
               
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 当前输入的内容是否存在省份直辖市列表中
        /// </summary>
        /// <param name="curInfo">当前需要查询的省份直辖市或城市</param>
        /// <param name="ht">当前需要查询省份直辖市或城市的Hashtable表</param>
        /// <returns>返回当前查询省份直辖市或城市对应的编码</returns>
        private static string IsSameInfo(string curInfo, Hashtable ht)
        {
            string strTmp = string.Empty;
            if (!string.IsNullOrEmpty(curInfo) && ht!=null && ht.Count>0)
            {
                foreach (DictionaryEntry item in ht)
                {
                   
                    if (item.Value.ToString().Contains(curInfo))
                    {
                        strTmp= item.Key.ToString();
                    }
                }
            }
            return strTmp;
        }

        /// <summary>
        /// 获取信息并打印
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <returns></returns>
        private static Hashtable GetInfoAndPrint(string url)
        {
            Hashtable HTTmp = null;
            if (!string.IsNullOrEmpty(url))
            {
                string content = HttpGet(url);
                HTTmp = AnalayJson.AnalayJsonString(content);
               
                foreach (DictionaryEntry item in HTTmp)
                {
                    Console.WriteLine(item.Key + " " + item.Value);
                }
                Console.WriteLine("---------解析完成-------------");
            }
            return HTTmp;
        }

    }//Class_end

    class AnalayJson
    {
        #region   解析Json字符串(首尾没有中括号)
        /// <summary>
        /// 解析Json字符串(首尾没有中括号)【线程安全】
        /// </summary>
        /// <param name="jsonStr">需要解析的Json字符串</param>
        /// <returns>返回解析好的Hashtable表</returns>
        public static Hashtable AnalayJsonString(string jsonStr)
        {
            Hashtable ht = new Hashtable();
            if (!string.IsNullOrEmpty(jsonStr))
            {
                JObject jo = (JObject)JsonConvert.DeserializeObject(jsonStr);
                foreach (var item in jo)
                {
                    ht.Add(item.Key, item.Value);
                }
            }

            return ht;
        }

        /// <summary>
        /// 解析Json字符串为JObject(首尾没有中括号)
        /// </summary>
        /// <param name="jsonStr">需要解析的Json字符串</param>
        /// <returns>返回解析后的JObject对象</returns>
        public static JObject AnalayJsonStringToJObject(string jsonStr)
        {
            if (!string.IsNullOrEmpty(jsonStr))
            {
                string strJsonIndex = string.Empty;
                JObject jo = (JObject)JsonConvert.DeserializeObject(jsonStr);
                return jo;
            }
            else
            {
                return null;
            }
        }

        #endregion

        #region   解析Json字符串(首尾有中括号)

        /// <summary>
        /// 解析Json字符串(首尾有中括号)【线程安全】
        /// </summary>
        /// <param name="jsonStr">需要解析的Json字符串</param>
        /// <returns>返回解析好的Hashtable表</returns>
        public static Hashtable AnalayJsonStringMiddleBrackets(string jsonStr)
        {
            Hashtable ht = new Hashtable();
            if (!string.IsNullOrEmpty(jsonStr))
            {
                JArray jArray = (JArray)JsonConvert.DeserializeObject(jsonStr);//jsonArrayText必须是带[]字符串数组
                if (jArray != null && jArray.Count > 0)
                {
                    foreach (var item in jArray)
                    {
                        foreach (JToken jToken in item)
                        {
                            string[] strTmp = jToken.ToString().Split(':');
                            ht.Add(strTmp[0].Replace("\"", ""), strTmp[1].Replace("\"", ""));
                        }
                    }
                }
            }
            return ht;
        }

        /// <summary>
        /// 解析Json字符串为JArray(首尾有中括号)
        /// </summary>
        /// <param name="jsonStr">需要解析的Json字符串</param>
        /// <returns>返回解析后的JArray对象</returns>
        public static JArray AnalayJsonStringMiddleBracketsToJArray(string jsonStr)
        {
            if (!string.IsNullOrEmpty(jsonStr))
            {
                string strJsonIndex = string.Empty;
                JArray ja = (JArray)JsonConvert.DeserializeObject(jsonStr);
                return ja;
            }
            else
            {
                return null;
            }
        }

        #endregion
    }

1.2、获取中国免费的天气信息方式2

1.2.1、采用第三方直接提供的数据接口(我这里的是直接采用:和风天气做示例;还推荐中国气象数据网气象大数据平台

①打开和风天气官网和风天气,然后选择右上角的“天气API”

②进入天气API后如果没有登陆请先注册登陆

③注册登陆后选择“API文档”,如下图所示;

④查看对应的API文档了解用法

⑤查看API文档后需要注册自己需要使用天气信息应用的key,操作如下图所示:

 

1.2.2、采用和风天气API获取天气信息代码如下:

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Collections;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Text.RegularExpressions;

    class Program
    {
        static void Main(string[] args)
        {
            //获取天气信息
            GetWeatherInfos();

        }

        //获取天气信息
        private static void GetWeatherInfos()
        {
          
            try
            {

                //1-输入当前需要查询的地州名称
                string strAreaName = null;
                while (true)
                {
                    Console.Write("请输入需要查询的地州:");
                    strAreaName = Console.ReadLine();
                   
                    if (!string.IsNullOrEmpty(strAreaName)) break;
                }

                Console.WriteLine("当前查询的省市地州为:"+ strAreaName);


                //2-和风天气实时信息获取示例
                string WeatherInfo = HttpGet($"https://free-api.heweather.net/s6/weather/now?location={strAreaName}&key=5c742a5979914bc6b7e195180ab488ee");

                JObject jo = AnalayJson.AnalayJsonStringToJObject(WeatherInfo);
                string str = jo["HeWeather6"].ToString();
                JArray ja = AnalayJson.AnalayJsonStringMiddleBracketsToJArray(str);
                Console.WriteLine("1-体感温度:" + ja[0]["now"]["fl"]);
                Console.WriteLine("2-温度:" + ja[0]["now"]["tmp"] + "℃");
                Console.WriteLine("3-天气情况:" + ja[0]["now"]["cond_txt"]);
                Console.WriteLine("4-风向角度:" + ja[0]["now"]["wind_deg"] );
                Console.WriteLine("5-风向:" + ja[0]["now"]["wind_dir"] );
                Console.WriteLine("5-风速:" + ja[0]["now"]["wind_spd"] );
                Console.WriteLine("6-相对湿度:" + ja[0]["now"]["hum"] + "");
                Console.WriteLine("7-降水量:" + ja[0]["now"]["pcpn"] );
                Console.WriteLine("8-大气压强:" + ja[0]["now"]["pres"] + "pa");
                Console.WriteLine("9-能见度:" + ja[0]["now"]["vis"] + "公里");
                Console.WriteLine("10-云量:" + ja[0]["now"]["cloud"] );


                Console.WriteLine("-----------免费的天气信息获取完成----------------");


            Console.WriteLine("按任何键退出...");
            Console.ReadKey();
        }

        /// <summary>
        /// 发送GET请求
        /// </summary>
        /// <param name="url">请求URL,如果需要传参,在URL末尾加上“?+参数名=参数值”即可</param>
        /// <returns>返回对应的相应信息</returns>
        private static string HttpGet(string url)
        {
            if (!string.IsNullOrEmpty(url))
            {
                try
                {
                    //创建
                    HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                    //设置请求方法
                    httpWebRequest.Method = "GET";
                    //请求超时时间
                    httpWebRequest.Timeout = 20000;
                    //发送请求
                    HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    //利用Stream流读取返回数据
                    StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
                    //获得最终数据,一般是json
                    string responseContent = streamReader.ReadToEnd();
                    streamReader.Close();
                    httpWebResponse.Close();
                    return responseContent;
                }
                catch (Exception ex)
                {

                    throw new Exception("获取当前 "+url+" 信息出错,请检查!!!"+ex.Message);
                }
               
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 当前输入的内容是否存在省份直辖市列表中
        /// </summary>
        /// <param name="curInfo">当前需要查询的省份直辖市或城市</param>
        /// <param name="ht">当前需要查询省份直辖市或城市的Hashtable表</param>
        /// <returns>返回当前查询省份直辖市或城市对应的编码</returns>
        private static string IsSameInfo(string curInfo, Hashtable ht)
        {
            string strTmp = string.Empty;
            if (!string.IsNullOrEmpty(curInfo) && ht!=null && ht.Count>0)
            {
                foreach (DictionaryEntry item in ht)
                {
                   
                    if (item.Value.ToString().Contains(curInfo))
                    {
                        strTmp= item.Key.ToString();
                    }
                }
            }
            return strTmp;
        }

        /// <summary>
        /// 获取信息并打印
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <returns></returns>
        private static Hashtable GetInfoAndPrint(string url)
        {
            Hashtable HTTmp = null;
            if (!string.IsNullOrEmpty(url))
            {
                string content = HttpGet(url);
                HTTmp = AnalayJson.AnalayJsonString(content);
               
                foreach (DictionaryEntry item in HTTmp)
                {
                    Console.WriteLine(item.Key + " " + item.Value);
                }
                Console.WriteLine("---------解析完成-------------");
            }
            return HTTmp;
        }

    }//Class_end

    class AnalayJson
    {
        #region   解析Json字符串(首尾没有中括号)
        /// <summary>
        /// 解析Json字符串(首尾没有中括号)【线程安全】
        /// </summary>
        /// <param name="jsonStr">需要解析的Json字符串</param>
        /// <returns>返回解析好的Hashtable表</returns>
        public static Hashtable AnalayJsonString(string jsonStr)
        {
            Hashtable ht = new Hashtable();
            if (!string.IsNullOrEmpty(jsonStr))
            {
                JObject jo = (JObject)JsonConvert.DeserializeObject(jsonStr);
                foreach (var item in jo)
                {
                    ht.Add(item.Key, item.Value);
                }
            }

            return ht;
        }

        /// <summary>
        /// 解析Json字符串为JObject(首尾没有中括号)
        /// </summary>
        /// <param name="jsonStr">需要解析的Json字符串</param>
        /// <returns>返回解析后的JObject对象</returns>
        public static JObject AnalayJsonStringToJObject(string jsonStr)
        {
            if (!string.IsNullOrEmpty(jsonStr))
            {
                string strJsonIndex = string.Empty;
                JObject jo = (JObject)JsonConvert.DeserializeObject(jsonStr);
                return jo;
            }
            else
            {
                return null;
            }
        }

        #endregion

        #region   解析Json字符串(首尾有中括号)

        /// <summary>
        /// 解析Json字符串(首尾有中括号)【线程安全】
        /// </summary>
        /// <param name="jsonStr">需要解析的Json字符串</param>
        /// <returns>返回解析好的Hashtable表</returns>
        public static Hashtable AnalayJsonStringMiddleBrackets(string jsonStr)
        {
            Hashtable ht = new Hashtable();
            if (!string.IsNullOrEmpty(jsonStr))
            {
                JArray jArray = (JArray)JsonConvert.DeserializeObject(jsonStr);//jsonArrayText必须是带[]字符串数组
                if (jArray != null && jArray.Count > 0)
                {
                    foreach (var item in jArray)
                    {
                        foreach (JToken jToken in item)
                        {
                            string[] strTmp = jToken.ToString().Split(':');
                            ht.Add(strTmp[0].Replace("\"", ""), strTmp[1].Replace("\"", ""));
                        }
                    }
                }
            }
            return ht;
        }

        /// <summary>
        /// 解析Json字符串为JArray(首尾有中括号)
        /// </summary>
        /// <param name="jsonStr">需要解析的Json字符串</param>
        /// <returns>返回解析后的JArray对象</returns>
        public static JArray AnalayJsonStringMiddleBracketsToJArray(string jsonStr)
        {
            if (!string.IsNullOrEmpty(jsonStr))
            {
                string strJsonIndex = string.Empty;
                JArray ja = (JArray)JsonConvert.DeserializeObject(jsonStr);
                return ja;
            }
            else
            {
                return null;
            }
        }

        #endregion
    }

运行结果如下:

 

 

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牛奶咖啡13

我们一起来让这个世界有趣一点…

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值