[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('-', ));
- 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('-', ));
- }
- 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
[C#]使用控制台获取天气预报的更多相关文章
- [整]C#获取天气预报信息(baidu api)包括pm2.5
/// <summary> /// 获取天气预报信息 /// </summary> /// <returns></returns> public Bai ...
- java获取天气预报的信息
运行效果: 主要功能: 1,jsp页面输入省份和城市 根据条件获取当地的天气信息 2,java代码 利用第三方的省份和城市的路径地址 本工程主要实现java获取天气预报的信息步骤1,创建工程weath ...
- Android 获取天气预报
界面布局 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android ...
- php从气象局获取天气预报并保存到服务器
思路:1.打开网页时读取中国气象网的接口得到每个城市的该日json:2.解析并保存到mysql:3.客户端访问mysql得到数据集. 所包含的技巧: 进度条.flush()问题.mysql.xml.p ...
- springboot 采用HttpClient获取天气预报 异常及原因
采用httpClient调用天气预报地址获取出现异常 2018-10-04 15:18:25.815 ERROR 10868 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[ ...
- Ajax的封装,以及利用jquery的ajax获取天气预报
1.Ajax的封装 function ajax(type,url,param,sync,datetype,callback){//第一个参数是获取数据的类型,第二个参数是传入open的url,第三个是 ...
- 获取天气预报API5_统计最容易生病时间段
sklearn实战-乳腺癌细胞数据挖掘(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&a ...
- 获取天气预报API
sklearn实战-乳腺癌细胞数据挖掘(博主亲自录制视频) https://study.163.com/course/introduction.htm?courseId=1005269003& ...
- 跨域使用jsonp 获取天气预报
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> ...
随机推荐
- CKEditor 集成CKFinder集成
lCKEditor原名FckEditor,著名的HTML编辑器,可以在线编辑HTML内容,演示一下.打开.自己人用CKEditor,网友用UBBEditor. l配置参考文档,主要将ckeditor中 ...
- 安装spark单机环境
(假定已经装好的hadoop,不管你装没装好,反正我是装好了) 1 下载spark安装包 http://spark.apache.org/downloads.html 下载spark-1.6.1-bi ...
- JavaScript学习点滴 call、apply的区别
对于apply和call两者在作用上是相同的,但两者在参数上有区别的. 1.call call 方法 调用一个对象的一个方法,以另一个对象替换当前对象. call([thisObj[,arg1 ...
- 关于使用Log4Net将日志插入oracle数据库中
1.关于配置文件. <?xml version="1.0" encoding="utf-8" ?> <configuration> &l ...
- sql查询化繁为简 告别rs.getString("XX"),bean属性赋值setXX("XX")
一.在执行sql语句查询时候,查询的结果是set的map集合(ResultSet): 结果使用rs.getString("XX")获得对应属性的值,赋值到bean对象的相应的属性中 ...
- Selectize使用总结
一.简介 Selectize是一个可扩展的基于jQuery 的自定义下拉框的UI控件.它对展示标签.联系人列表.国家选择器等比较有用.它的大小在~ 7kb(gzip压缩)左右.提供一个可靠且体验良好的 ...
- vuex 基本用法、兄弟组件通信,参数传递
vuex主要是是做数据交互,父子组件传值可以很容易办到,但是兄弟组件间传值,需要先将值传给父组件,再传给子组件,异常麻烦. vuex大概思路:a=new Vue(),发射数据'msg':a.$emit ...
- Kotlin——最详细的操作符与操作符重载详解(上)
本篇文章为大家详细的介绍Koltin特有的操作符重载.或许对于有编程经验的朋友来说,操作符这个词绝对不陌生,就算没有任何编辑基础的朋友,数学中的算数运算符也绝不陌生.例如(+.-.*./.>.& ...
- 如何把kotlin+spring boot开发的项目部署在tomcat上
本文只讲部署过程,你首先要保证你的程序能在IDE里跑起来: 先看看你的application.properties中设置的端口号与你服务器上tomcat的端口号是否一致 server.port=80 ...
- 前端工程之CDN部署
之前发的一篇文章<变态的静态资源缓存与更新>中提到了静态资源和页面部署之间的时间间隙问题,这个问题会迫使前端静态资源发布必须采用非覆盖式. 那篇文章中没有详细解释为什么会产生不可忍受的时间 ...