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

来源:https://www.cnblogs.com/cncc/archive/2018/01/24/8342884.html
-Advertisement-
Play Games

本例子主要是使用由中央氣象局網站(http://www.nmc.gov.cn)提供的JSON API,其實現思路如下: 1、訪問獲取省份(包含直轄市、自治區等,以下簡稱省份)的網址(http://www.nmc.gov.cn/f/rest/province),返回對應的省份名稱(name)、代碼(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/1pM98VnP
可執行應用程式:https://pan.baidu.com/s/1i6mK8xn

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 以前的項目格式使用的是 csproj 的格式,但是 .net core 支持使用 project.json 格式的項目文件,後來還是決定不使用這個格式。 VS2017 的項目格式更好讀、更簡單而且減少了 git 衝突。 本文來告訴大家如何從 VS2015 和以前的項目格式修改為 VS2017 項目... ...
  • (1)下載erlang: http://www.erlang.org/download/otp_win64_17.3.exe 並安裝 (2)下載RabbitMQ: http://www.rabbitmq.com/ 並安裝 (3)下載並安裝好後找到服務啟動選項並打開rabbitmq服務 至此,rabb ...
  • 【先上一張效果圖】: 一、原理: 其實原理很簡單: 1.手機投屏到電腦; 2.截取投屏畫面的題目部分,進行識別,得到題目和三個答案; 3.將答案按照一定的演算法,進行搜索,得出推薦答案; 4.添加了一些其他輔助功能,比如:瀏覽器搜索結果展示、關鍵字高亮、瀏覽器可點擊等; 二、二營長,把我的義大利... ...
  • 最近花時間弄了一個關於fireasy使用的demo,已放到 github 上供大家研究,https://github.com/faib920/zero 該 demo 演示瞭如何使用 fireasy 創建一個後臺的管理系統。解決方案包含 asp.net mvc5 和 asp.net core 兩個示例 ...
  • 演示產品源碼下載地址:http://www.jinhusns.com ...
  • 演示產品源碼下載地址:http://www.jinhusns.com ...
  • 1. 前言 在 "如何使用Fluent Design System" 這篇文章里已經簡單介紹過Reveal的用法,這篇再詳細介紹其它內容。 自Windows 8 放棄Aero後,群眾對毛玻璃回歸的呼聲一致都很大。Fluent Design System帶來了新的透明背景Acrylic,提供更好的性能 ...
  • 為了幫助大家更深刻地認識Dora.Interception,並更好地將它應用到你的項目中,我們通過如下幾個簡單的實例來演示幾個常見的AOP應用在Dora.Interception下的實現。對於下麵演示的實例,它們僅僅是具有指導性質的應用,所以我會儘可能地簡化,如果大家需要將相應的應用場景移植到具體的... ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...