日期:2014-05-18  浏览次数:20381 次

请用过WebService引用新浪的天气预报的帮忙看看
以下是获取天气预报的WebService代码:

[WebMethod]
        public   string   GetWeather(string   city)   {
                string   weacherhtml   =   String.Empty;
                //转换输入参数的编码类型
                string   mycity   =   System.Web.HttpUtility.UrlEncode(city,   System.Text.UnicodeEncoding.GetEncoding( "GB2312 "));
                //初始化新的   WebRequest
                HttpWebRequest   webrt   =   (HttpWebRequest)WebRequest.Create( "http://php.weather.sina.com.cn/search.php?city= "   +   mycity);
                //返回对   Internet   请求的响应
                HttpWebResponse   webrs   =   (HttpWebResponse)webrt.GetResponse();
                //从   Internet   资源返回数据流
                Stream   stream   =   webrs.GetResponseStream();

                //读取数据流
                StreamReader   srm   =   new   StreamReader(stream,   System.Text.Encoding.Default);
                //从头读到尾,把数据读到   weacherhtml   中
                weacherhtml   =   srm.ReadToEnd();
                //关闭打开的资源
                srm.Close();
                stream.Close();
                webrs.Close();
                //针对不同的网站,以下的开始部分和结束部分不同
                //可通过查看网站的源文件解决
                int   start   =   weacherhtml.IndexOf( "城市天气   begin ");
                int   end   =   weacherhtml.IndexOf( "城市天气   end ");
                //返回一个HTML的Table,预报城市天气
                return   weacherhtml.Substring(start   +   14,   end   -   start);
        }

当参数city给了 "北京 "这个值后调用此方法,却没有返回天气预报信息。现在我怀疑其中的int   start   =   weacherhtml.IndexOf( "城市天气   begin ");
                int   end   =   weacherhtml.IndexOf( "城市天气   end ");
位置定位不正确,不知取新浪的天气信息该如何定位?谢谢指教!

------解决方案--------------------
这个是有不确定的时候,但只有2种时候.
它回自动变换位置,你可以获得长的字符串,加一个判断就可以了.