本例子主要是使用由中央气象局网站(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、源代码如下:

  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7.  
  8. namespace Weather
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. HttpWebRequest request = WebRequest.CreateHttp(@"http://www.nmc.gov.cn/f/rest/province");
  15. try
  16. {
  17. HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  18. Stream stream = response.GetResponseStream();
  19. StreamReader reader = new StreamReader(stream);
  20. string content = reader.ReadToEnd();
  21. List<Province> provinceResult = JsonConvert.DeserializeObject<List<Province>>(content);
  22. Dictionary<string, string> proviceNamedict = new Dictionary<string, string>();
  23. Console.WriteLine("省及直辖市:");
  24. provinceResult.ForEach(x =>
  25. {
  26. proviceNamedict.Add(x.name, x.code);
  27. Console.WriteLine(x.name);
  28. });
  29. string provice;
  30. while (true)
  31. {
  32. Console.Write("请输入需要查询的省或直辖市:");
  33. provice = Console.ReadLine();
  34. if (proviceNamedict.Keys.Contains(provice)) break;
  35. }
  36. Console.Clear();
  37. request = WebRequest.CreateHttp($"http://www.nmc.gov.cn/f/rest/province/{proviceNamedict[provice]}");
  38. response = request.GetResponse() as HttpWebResponse;
  39. stream = response.GetResponseStream();
  40. reader = new StreamReader(stream);
  41. content = reader.ReadToEnd();
  42. List<City> cityResult = JsonConvert.DeserializeObject<List<City>>(content);
  43. Dictionary<string, string> cityNamedict = new Dictionary<string, string>();
  44. Console.WriteLine("城市:");
  45. cityResult.ForEach(x =>
  46. {
  47. cityNamedict.Add(x.city, x.code);
  48. Console.WriteLine(x.city);
  49. });
  50. string city;
  51. while (true)
  52. {
  53. Console.Write("请输入需要查询的城市:");
  54. city = Console.ReadLine();
  55. if (cityNamedict.Keys.Contains(city)) break;
  56. }
  57. request = WebRequest.CreateHttp($"http://www.nmc.gov.cn/f/rest/real/{cityNamedict[city]}");
  58. response = request.GetResponse() as HttpWebResponse;
  59. stream = response.GetResponseStream();
  60. reader = new StreamReader(stream);
  61. content = reader.ReadToEnd();
  62. Detail detailResult = JsonConvert.DeserializeObject<Detail>(content);
  63. Console.WriteLine(new string('-', ));
  64. Console.WriteLine("详细情况如下:");
  65. Console.WriteLine($"{detailResult.station.province},{detailResult.station.city} 发布时间:{detailResult.publish_time}");
  66. Console.WriteLine($"温度:{detailResult.weather.temperature}℃ 温差:{detailResult.weather.temperatureDiff}℃ 气压:{detailResult.weather.airpressure}hPa 湿度:{detailResult.weather.humidity}% 雨量:{detailResult.weather.rain}mm");
  67. Console.WriteLine($"天气状况:{detailResult.weather.info}");
  68. Console.WriteLine($"风向:{detailResult.wind.direct} {detailResult.wind.power} 风速:{detailResult.wind.speed}m/s");
  69. Console.WriteLine(new string('-', ));
  70. }
  71. catch(WebException ex)
  72. {
  73. Console.WriteLine(ex.Message);
  74. }
  75. Console.WriteLine("按任何键退出...");
  76. Console.ReadKey();
  77. }
  78. }
  79.  
  80. class Province
  81. {
  82. public string code { set; get; }
  83. public string name { set; get; }
  84. public string url { set; get; }
  85. }
  86.  
  87. class City
  88. {
  89. public string url { set; get; }
  90. public string code { set; get; }
  91. public string city { set; get; }
  92. public string province { set; get; }
  93. }
  94.  
  95. class Detail
  96. {
  97. public City station { set; get; }
  98. public string publish_time { set; get; }
  99. public Weather weather { set; get; }
  100. public Wind wind { set; get; }
  101. public Warn warn { set; get; }
  102. }
  103.  
  104. class Weather
  105. {
  106. public float temperature { set; get; }
  107. public float temperatureDiff { set; get; }
  108. public float airpressure { set; get; }
  109. public float humidity { set; get; }
  110. public float rain { set; get; }
  111. public float rcomfort { set; get; }
  112. public float icomfort { set; get; }
  113. public string info { set; get; }
  114. public string img { set; get; }
  115. public float feelst { set; get; }
  116. }
  117.  
  118. class Wind
  119. {
  120. public string direct { set; get; }
  121. public string power { set; get; }
  122. public float speed { set; get; }
  123. }
  124. class Warn
  125. {
  126. public string alert { set; get; }
  127. public string pic { set; get; }
  128. public string province { set; get; }
  129. public string city { set; get; }
  130. public string url { set; get; }
  131. public string issuecontent { set; get; }
  132. public string fmeans { set; get; }
  133. }
  134. }

6、运行效果如下:

7、源代码与可执行应用程序如下:

  1. 可执行应用程序:https://pan.baidu.com/s/1i6mK8xn

[C#]使用控制台获取天气预报的更多相关文章

  1. [整]C#获取天气预报信息(baidu api)包括pm2.5

    /// <summary> /// 获取天气预报信息 /// </summary> /// <returns></returns> public Bai ...

  2. java获取天气预报的信息

    运行效果: 主要功能: 1,jsp页面输入省份和城市 根据条件获取当地的天气信息 2,java代码 利用第三方的省份和城市的路径地址 本工程主要实现java获取天气预报的信息步骤1,创建工程weath ...

  3. Android 获取天气预报

    界面布局 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android ...

  4. php从气象局获取天气预报并保存到服务器

    思路:1.打开网页时读取中国气象网的接口得到每个城市的该日json:2.解析并保存到mysql:3.客户端访问mysql得到数据集. 所包含的技巧: 进度条.flush()问题.mysql.xml.p ...

  5. springboot 采用HttpClient获取天气预报 异常及原因

    采用httpClient调用天气预报地址获取出现异常 2018-10-04 15:18:25.815 ERROR 10868 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[ ...

  6. Ajax的封装,以及利用jquery的ajax获取天气预报

    1.Ajax的封装 function ajax(type,url,param,sync,datetype,callback){//第一个参数是获取数据的类型,第二个参数是传入open的url,第三个是 ...

  7. 获取天气预报API5_统计最容易生病时间段

    sklearn实战-乳腺癌细胞数据挖掘(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&a ...

  8. 获取天气预报API

    sklearn实战-乳腺癌细胞数据挖掘(博主亲自录制视频) https://study.163.com/course/introduction.htm?courseId=1005269003& ...

  9. 跨域使用jsonp 获取天气预报

    <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">    ...

随机推荐

  1. CKEditor 集成CKFinder集成

    lCKEditor原名FckEditor,著名的HTML编辑器,可以在线编辑HTML内容,演示一下.打开.自己人用CKEditor,网友用UBBEditor. l配置参考文档,主要将ckeditor中 ...

  2. 安装spark单机环境

    (假定已经装好的hadoop,不管你装没装好,反正我是装好了) 1 下载spark安装包 http://spark.apache.org/downloads.html 下载spark-1.6.1-bi ...

  3. JavaScript学习点滴 call、apply的区别

    对于apply和call两者在作用上是相同的,但两者在参数上有区别的.     1.call call 方法 调用一个对象的一个方法,以另一个对象替换当前对象. call([thisObj[,arg1 ...

  4. 关于使用Log4Net将日志插入oracle数据库中

    1.关于配置文件. <?xml version="1.0" encoding="utf-8" ?> <configuration> &l ...

  5. sql查询化繁为简 告别rs.getString("XX"),bean属性赋值setXX("XX")

    一.在执行sql语句查询时候,查询的结果是set的map集合(ResultSet): 结果使用rs.getString("XX")获得对应属性的值,赋值到bean对象的相应的属性中 ...

  6. Selectize使用总结

    一.简介 Selectize是一个可扩展的基于jQuery 的自定义下拉框的UI控件.它对展示标签.联系人列表.国家选择器等比较有用.它的大小在~ 7kb(gzip压缩)左右.提供一个可靠且体验良好的 ...

  7. vuex 基本用法、兄弟组件通信,参数传递

    vuex主要是是做数据交互,父子组件传值可以很容易办到,但是兄弟组件间传值,需要先将值传给父组件,再传给子组件,异常麻烦. vuex大概思路:a=new Vue(),发射数据'msg':a.$emit ...

  8. Kotlin——最详细的操作符与操作符重载详解(上)

    本篇文章为大家详细的介绍Koltin特有的操作符重载.或许对于有编程经验的朋友来说,操作符这个词绝对不陌生,就算没有任何编辑基础的朋友,数学中的算数运算符也绝不陌生.例如(+.-.*./.>.& ...

  9. 如何把kotlin+spring boot开发的项目部署在tomcat上

    本文只讲部署过程,你首先要保证你的程序能在IDE里跑起来: 先看看你的application.properties中设置的端口号与你服务器上tomcat的端口号是否一致 server.port=80 ...

  10. 前端工程之CDN部署

    之前发的一篇文章<变态的静态资源缓存与更新>中提到了静态资源和页面部署之间的时间间隙问题,这个问题会迫使前端静态资源发布必须采用非覆盖式. 那篇文章中没有详细解释为什么会产生不可忍受的时间 ...