如何通过天气API获取天气信息
2019-01-11 09:17
218 查看
获取天气数据C#
利用HttpClient的GetAsync方法
- 发送http请求并获取数据
class GetJson { //目标链接 private string APIStr = "http://t.weather.sojson.com/api/weather/city/101030100"; public async Task<string> HttpGet() { //转化为url格式 Uri APIUri = new Uri(APIStr); //存储返回的json数据 string data = null; try { using (HttpClient httpClient = new HttpClient()) { //设置访问基址 //httpClient.BaseAddress = APIUri; //设置相应时间 TimeSpan timeOut = new TimeSpan(0, 0, 30); httpClient.Timeout = timeOut; httpClient.DefaultRequestHeaders.Accept.Clear(); //向服务器发送get请求 data = await httpClient.GetStringAsync(APIUri); } }//超时抓取 catch(ArgumentOutOfRangeException e) { return e.Message.ToString(); } return data; } }
- json数据的转化为本地对象
-
引入处理json的package:Newtonsoft.Json
- 建立包含json相同数据相同的属性类
//报文结构状态 public class JsonInfo { public DateTime time { get; set; } public CityInfo cityinfo { get; set; } public string date { get; set; } public string message { get; set; } public string status { get; set; } public Data data { get; set; } } #region 详细数据 //城市信息 public class CityInfo { public string city { get; set; } public string cityId { get; set; } public string parent { get; set; } public string upadataTime { get; set; } } //今天信息 public class Data { public string shidu { get; set; } public string pm25 { get; set; } public 1c6f3 string pm10 { get; set; } public string quality { get; set; } public string wendu { get; set; } public string ganmao { get; set; } public WeatherData yesterday { get; set; } public List<WeatherData> forecast { get; set; } } //预测信息 public class WeatherData { public string date { get; set; } public string sunrise { get; set; } public string high { get; set; } public string low { get; set; } //空气污染指数 public string aqi { get; set; } public DateTime ymd { get; set; } public string week { get; set; } //风向 public string fx { get; set; } //风级 public string fl { get; set; } //天气 public string type { get; set; } //提醒 public string notice { get; set; } } #endregion
- 转化成对象:
public class JsonStrDel { public JsonInfo WeatherMessage; public void DataDel(string jsonMessage ) { //反序列化 WeatherMessage=JsonConvert.DeserializeObject<JsonInfo>(jsonMessage); } }
源代码下载:https://github.com/xiaoxianrou8/GetPost
相关文章推荐
- GOOGLE MAP API 如何通过经纬度获取地址信息?
- android通过google api获取天气信息示例
- QT通过API获取天气信息
- Qt通过api获取天气信息
- C# 网络编程之通过豆瓣API获取书籍信息
- 如何通过经纬度获取地址信息?
- android中国天气网api获取天气信息并解析
- hadoop2.0(chd4) 通过API获取job信息
- 如何通过adb命令获取手机型号与设备信息
- SqlServer如何通过SQL语句获取处理器(CPU)、内存(Memory)、磁盘(Disk)以及操作系统相关信息
- 如何通过adb命令获取手机型号与设备信息
- 通过快递100 api 获取物流信息
- 网络API下获取天气json数据信息
- 如何通过豆瓣API获取图书和电影列表
- Android使用"中国天气网"API数据通过城市名称获取天气情况
- Android使用"中国天气网"API数据通过城市名称获取天气情况
- 通过百度地图实现定位并获取本地当日天气信息
- 通过快递100 api 获取物流信息
- Java通过webservice接口获取天气信息
- 如何利用Java获取进程的信息(通过tasklist和cmd与Windows进行交互)