中國天氣網接口地址:”http://wthrcdn.etouch.cn/WeatherApi?citykey=” + weatherCityCode(為城市code);
下面是轉化過程中我們需要用到的方法(序列化的實體類在文章結尾附)
string weatherInfoUrl = "http://wthrcdn.etouch.cn/WeatherApi?citykey=" + weatherCityCode; string weatherstr = getHtml2(weatherInfoUrl); resp tempInfo = XmlDeSeralizer<resp>(weatherstr);
轉化過程中需要用到的方法
private static string GetHtml(string url) { StringBuilder s = 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) { s.Append(Encoding.UTF8.GetString(d, 0, l)); l = g.Read(d, 0, 20480); } return s.ToString(); } 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; } }
天氣實體類
public class resp { public string city { get; set; } public string updatetime { get; set; } public string wendu { get; set; } public string fengli { get; set; } public string shidu { get; set; } public string fengxiang { get; set; } public environment environment { get; set; } public alarm alarm { get; set; } public List<weather> forecast { set; get; } } public class environment { public string aqi { get; set; } public string pm25 { get; set; } public string suggest { get; set; } public string quality { get; set; } public string MajorPollutants { get; set; } public string time { get; set; } } public class alarm { public string cityName { get; set; } public string alarmType { get; set; } public string alarmDegree { get; set; } public string alarmText { get; set; } public string alarm_details { get; set; } public string standard { get; set; } public string suggest { get; set; } } public class weather { public string date { get; set; } public string high { get; set; } public string low { get; set; } public climate day { get; set; } public climate night { get; set; } } public class climate { public string type { get; set; } public string fengxiang { get; set; } public string fengli { get; set; } }