获取指定城市代码的城市天气

public static Weather GetCurrentWeather(string CityCode)
    {
        try
        {
            Uri myUri = new Uri("http://weather.news.qq.com/inc/ss" + CityCode + ".htm");

            HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(myUri);

            myWebRequest.Method = "GET";

            HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();

            StreamReader reader = new StreamReader(myWebResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312"));

            byte[] buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(reader.ReadToEnd());
            String HTML = System.Text.Encoding.GetEncoding("GB2312").GetString(buffer).Trim();
            String temp = "";
            int start, stop;

            start = HTML.IndexOf("</style>", 0, HTML.Length);

            stop = HTML.IndexOf("<script>", 0, HTML.Length);
            temp = HTML.Substring(start, stop - start);
            Regex regex = new Regex("<[^>]*>");
            string[] ss = regex.Split(temp);
            string t = "";
            foreach (string p in ss)
                if (p.Trim().Length > 0)
                    t += p + "/";
            string[] sss = t.Split('/');
            Weather weather = new Weather();
            if (sss.Length > 0) weather.City = sss[0];
            if (sss.Length > 1) weather.TodayWeather = sss[1];
            if (sss.Length > 2) weather.WenDu = sss[2];
            if (sss.Length > 3) weather.FengLi = sss[3];
            if (sss.Length > 4) weather.ZiWaiXian = sss[4];
            if (sss.Length > 5) weather.KongQi = sss[5];
            reader.Close();
            myWebResponse.Close();
            return weather;
        }
        catch
        {
            Weather w = new Weather();
            w.City = "-1";
            return w;
        }
 }

posted @ 2008-10-23 21:52  Jason.Bird  阅读(507)  评论(0编辑  收藏  举报