[C#]使用控制台獲取天氣預報


本例子主要是使用由中央氣象局網站(http://www.nmc.gov.cn)提供的JSON API,其實現思路如下:

1、訪問獲取省份(包含直轄市、自治區等,以下簡稱省份)的網址(http://www.nmc.gov.cn/f/rest/province),返回對應的省份名稱(name)、代碼(code)等,如下圖所示:

2、根據以上返回的代碼(code),將代碼拼接在網址(http://www.nmc.gov.cn/f/rest/province)的后面,如返回的代碼為 AGD (廣東省),則拼接后的網址為http://www.nmc.gov.cn/f/rest/province/AGD,以此獲得對應的城市名稱(city)、代碼(code),如下圖所示:

 

3、根據以上返回的代碼,將代碼拼接在網址(http://www.nmc.gov.cn/f/rest/real/)的后面,如返回的代碼為 59287 (廣州),則拼接后的網址為http://www.nmc.gov.cn/f/rest/real/59287,以此獲得對應的天氣信息,如下圖所示:

 

4、本例子使用的技術為 HttpWebRequest類、HttpWebResponse類及Newtonsoft.Json.JsonConvert類的使用,自己有不懂的,請自行進行百度;

5、源代碼如下:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;

namespace Weather
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpWebRequest request = WebRequest.CreateHttp(@"http://www.nmc.gov.cn/f/rest/province");
            try
            {
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                string content = reader.ReadToEnd();
                List<Province> provinceResult = JsonConvert.DeserializeObject<List<Province>>(content);
                Dictionary<string, string> proviceNamedict = new Dictionary<string, string>();
                Console.WriteLine("省及直轄市:");
                provinceResult.ForEach(x =>
                {
                    proviceNamedict.Add(x.name, x.code);
                    Console.WriteLine(x.name);
                });
                string provice;
                while (true)
                {
                    Console.Write("請輸入需要查詢的省或直轄市:");
                    provice = Console.ReadLine();
                    if (proviceNamedict.Keys.Contains(provice)) break;
                }
                Console.Clear();
                request = WebRequest.CreateHttp($"http://www.nmc.gov.cn/f/rest/province/{proviceNamedict[provice]}");
                response = request.GetResponse() as HttpWebResponse;
                stream = response.GetResponseStream();
                reader = new StreamReader(stream);
                content = reader.ReadToEnd();
                List<City> cityResult = JsonConvert.DeserializeObject<List<City>>(content);
                Dictionary<string, string> cityNamedict = new Dictionary<string, string>();
                Console.WriteLine("城市:");
                cityResult.ForEach(x =>
                {
                    cityNamedict.Add(x.city, x.code);
                    Console.WriteLine(x.city);
                });
                string city;
                while (true)
                {
                    Console.Write("請輸入需要查詢的城市:");
                    city = Console.ReadLine();
                    if (cityNamedict.Keys.Contains(city)) break;
                }
                request = WebRequest.CreateHttp($"http://www.nmc.gov.cn/f/rest/real/{cityNamedict[city]}");
                response = request.GetResponse() as HttpWebResponse;
                stream = response.GetResponseStream();
                reader = new StreamReader(stream);
                content = reader.ReadToEnd();
                Detail detailResult = JsonConvert.DeserializeObject<Detail>(content);
                Console.WriteLine(new string('-', 50));
                Console.WriteLine("詳細情況如下:");
                Console.WriteLine($"{detailResult.station.province},{detailResult.station.city} 發布時間:{detailResult.publish_time}");
                Console.WriteLine($"溫度:{detailResult.weather.temperature}℃ 溫差:{detailResult.weather.temperatureDiff}℃ 氣壓:{detailResult.weather.airpressure}hPa 濕度:{detailResult.weather.humidity}% 雨量:{detailResult.weather.rain}mm");
                Console.WriteLine($"天氣狀況:{detailResult.weather.info}");
                Console.WriteLine($"風向:{detailResult.wind.direct} {detailResult.wind.power} 風速:{detailResult.wind.speed}m/s");
                Console.WriteLine(new string('-', 50));
            }
            catch(WebException ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("按任何鍵退出...");
            Console.ReadKey();
        }
    }

    class Province
    {
        public string code { set; get; }
        public string name { set; get; }
        public string url { set; get; }
    }

    class City
    {
        public string url { set; get; }
        public string code { set; get; }
        public string city { set; get; }
        public string province { set; get; }
    }

    class Detail
    {
        public City station { set; get; }
        public string publish_time { set; get; }
        public Weather weather { set; get; }
        public Wind wind { set; get; }
        public Warn warn { set; get; }
    }

    class Weather
    {
        public float temperature { set; get; }
        public float temperatureDiff { set; get; }
        public float airpressure { set; get; }
        public float humidity { set; get; }
        public float rain { set; get; }
        public float rcomfort { set; get; }
        public float icomfort { set; get; }
        public string info { set; get; }
        public string img { set; get; }
        public float feelst { set; get; }
    }

    class Wind
    {
        public string direct { set; get; }
        public string power { set; get; }
        public float speed { set; get; }
    }
    class Warn
    {
        public string alert { set; get; }
        public string pic { set; get; }
        public string province { set; get; }
        public string city { set; get; }
        public string url { set; get; }
        public string issuecontent { set; get; }
        public string fmeans { set; get; }
    }
}

6、運行效果如下:

7、源代碼與可執行應用程序如下:

可執行應用程序:https://pan.baidu.com/s/1i6mK8xn

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM