[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"> ...
随机推荐
- python3.5 + PyQt5 +Eric6 实现的一个计算器
目前可以实现简单的计算.计算前请重置,设计的时候默认数字是0,学了半天就做出来个这么个结果,bug不少. python3.5 + PyQt5 +Eric6 在windows7 32位系统可以完美运行 ...
- 伽罗瓦域(有限域)GFq^12上元素的1→2→4→12塔式扩张(2)------第二次扩张
接上文https://www.cnblogs.com/heshuchao/p/8196307.html 继续探讨塔式扩张的第二部分,即1→2→4→12中2 → 4的元素扩张表示方式与计算公式推导. 3 ...
- QA问答系统,QA匹配论文学习笔记
论文题目: WIKIQA: A Challenge Dataset for Open-Domain Question Answering 论文代码运行: 首先按照readme中的提示安装需要的部分 遇 ...
- 一个好用的PHOTOSHOP切图插件(CutterMan插件下载)
请关注CutterMan官方微博,分享本站点到自己微博中@Cutterman,私信TA,就有啦~~ 下载地址:http://www.cutterman.cn/ 也许你兴冲冲的下载了,然后发现安装不上, ...
- 面向对象 初级版 (Preview) 未完
概述: 面向过程:根据业务逻辑从上到下写垒代码 函数式:将某功能代码封装到函数里,日后使用无需重复编写,直接调用韩顺即可. 面向对象: 对函数进行分类和封装,让开发'更快更强' 面向对象和面向过程的通 ...
- Extjs入门-grid
function rowdblclickFn(grid, rowIndex, e){//双击事件 var row = grid.store.getById(grid.stor ...
- 执行查询“BACKUP LOG [XXX] TO DISK = N'F:\\BackData\\事务日至备份\\...”失败,错误如下:“无法执行 BACKUP LOG,因为当前没有数据库备份。 BACKUP LOG 正在异常终止。
执行查询"BACKUP LOG [XXX] TO DISK = N'F:\\BackData\\事务日至备份\\..."失败,错误如下:"无法执行 BACKUP LOG ...
- select超链接跳转A
客户端页面 实现 下拉菜单 跳转链接 如图 遂使用 select option来展现.开始想到添加 a标签,结果,不行.渲染不出来 搜索查询得知 如下方法实现 ================== & ...
- Qt 地址薄 (二) 添加地址
在上一篇 Qt 地址薄 (一) 界面设计 中,主要是实现了地址簿的界面,使用布局管理器进行元素的布局,并解释了"子类化" 和"所有权"的概念. 本篇将在上面的基 ...
- 【转载】MySQL之权限管理
一.MySQL权限简介 关于mysql的权限简单的理解就是mysql允许你做你全力以内的事情,不可以越界.比如只允许你执行select操作,那么你就不能执行update操作.只允许你从某台机器上连接m ...