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
    }

運行結果如下:

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章