因为之前程序需要获取天气信息,优快云上也试了好多,最后取万家之所长终于搞定了!!!!
不说废话,直接上源码
1.实体类:只需要提取温度,天气和PM2.5.
//数据实体
public class resp
{
public string wendu { get; set; }
public environment environment { get; set; }
public climate climate { get; set; }
public List<weather> forecast { set; get; }
}
//获取PM2.5
public class environment
{
public string aqi { get; set; }
}
//获取昼夜
public class climate
{
public string type { get; set; }
}
//获取天气情况
public class weather
{
public climate day { get; set; }
public climate night { get; set; }
}
2.帮助类:解析返回的数据
private static void head(HttpWebResponse r)
{
string[] keys = r.Headers.AllKeys; for (int i = 0; i < keys.Length; ++i)
{
Console.WriteLine(keys[i] + " " + r.Headers[keys[i]]);
}
}
public static T XmlDeSeralizer<T>(string xmlStr) where T : class, new()
{
XmlSerializer xs = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xmlStr))
{
return xs.Deserialize(reader) as T;
}
}
3.实现类:获取天气信息方法[其中l1:温度,l2:pm2.5,l3:天气情况]
public void GetWerter()
{
//中国天气网信息[这个citykey就不用多说了吧,F12懂就懂了,不懂百度搜索关键字<城市ID>]
string url = "http://wthrcdn.etouch.cn/WeatherApi?citykey=101270101";//默认是四川成都
StringBuilder sb = new StringBuilder(102400);
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
head(response);
GZipStream g = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress);
byte[] d = new byte[20480];
int l = g.Read(d, 0, 20480);
while (l > 0)
{
sb.Append(Encoding.UTF8.GetString(d, 0, l));
l = g.Read(d, 0, 20480);
}
resp temp = XmlDeSeralizer<resp>(sb.ToString());
l1.Text = temp.wendu+"°";
l2.Text ="PM:"+temp.environment.aqi;
int time =DateTime.Now.Hour;
//中国天气网默认为8-20点为白天,Time属性里面有day与night。
if (time >8&&time<20)
{
l3.Text = temp.forecast[0].day.type;
}
else
{
l3.Text = temp.forecast[0].night.type;
}
}