概述
网上有很多种去获取天气信息的API,有的通过城市名,城市编码等获取,信息复杂度也各不相同。且有的要收费,有访问限制,所以具体看需求而定。
本文主要叙述通过中国天气网的API去获取简单的天气信息。
需求分析
基于便签项目的需求,我只需要根据所在的城市显示城市名+天气+最高、低气温,所以数据很简单。经过网上搜索,发觉中国天气网的API就很合适我。
API:http://www.weather.com.cn/data/cityinfo/101300301.html
返回数据:
{
weatherinfo:{
city:"柳州",
cityid:"101300301",
temp1:"23℃",
temp2:"30℃",
weather:"大到暴雨",
img1:"n23.gif",
img2:"d23.gif",
ptime:"18:00"
}
}
根据API可以看得出来,该方式需要传入一个城市编码,例如柳州编码为101300301,则只需要根据相应的城市名去获取相应编码即可。数据为JSON格式,使用Newstonsoft.json去解析,获取想要的字段即可。
代码实现
开始我们需要将获取到的省市两个字段,然后将其传入方法,与本地的城市编码数据比对,获得城市编码。该文件数据结构大概是这样 :
城市编码JSON文件结构
我把它放在GitHub上,有需要的可以去down下来:中国天气网城市编码JSON
代码中涉及到一些数据对象就不展示了,大家根据JSON数据创建即可
public string GetCityCode(AddressComponent address)
{
//解析本地的中国天气网城市编码文件
GetWeatherCodeData data = JsonConvert.DeserializeObject<GetWeatherCodeData>(MMY.StickyNote.UI.Properties.Resources.WeatherCode);
//获得传入的省的前两个字符
string tempGetProvince = address.province.Substring(0, 2);
//获得传入的市的前两个字符
string tempGetCity = address.city.Substring(0, 2);
string cityCode = "0";
//Console.WriteLine(tempGetProvince);
//遍历查找对应的城市编码
foreach (var item_p in data.城市代码)
{
//Console.WriteLine(item_p.省);
string tempLocalProvince = item_p.省.Substring(0, 2);
if (tempGetProvince == tempLocalProvince)
{
foreach (var item_c in item_p.市)
{
string tempLocalCity = item_c.市名.Substring(0, 2);
if (tempGetCity == tempLocalCity)
{
cityCode = item_c.编码;
}
}
}
}
return cityCode;
}
然后使用上述方法返回的城市编码到下方拼接后请求,获取解析数据。
public WeatherInfoData GetWeatherData( string code)
{
//***********http://www.weather.com.cn/data/cityinfo/101110101.html
string staticAddress = "http://www.weather.com.cn/data/cityinfo/";
//拼接API Url
string url = String.Format("{0}{1}.html",staticAddress, code);
//请求Url
string result = Get(url);
//Console.WriteLine(result);
//解析数据,返回天气数据对象
GetWheatherLocalData data = JsonConvert.DeserializeObject<GetWheatherLocalData>(result);
//Console.WriteLine(data.weatherinfo.weather);
return data.weatherinfo;
}
private string Get(string url)
{
string result = string.Empty;
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result;
result = response.Content.ReadAsStringAsync().Result;
}
return result;
}
效果
展示效果












网友评论