HttpWebRequest实现读取天气预报信息

<HTML>
    <HEAD>
        <title>Weather</title>
        <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
        <meta content="C#" name="CODE_LANGUAGE">
        <meta content="JavaScript" name="vs_defaultClientScript">
        <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
            <TABLE id="Table1" style="Z-INDEX: 110; LEFT: 296px; WIDTH: 320px; POSITION: absolute; TOP: 24px; HEIGHT: 231px"
                cellSpacing="1" cellPadding="1" width="320" bgColor="#ffff99" border="1">
                <TR>
                    <TD><asp:label id="Label1" runat="server" Font-Italic="True">==天气预报==</asp:label></TD>
                    <TD><asp:dropdownlist id="ddlcity" runat="server">
                            <asp:ListItem Value="深圳" Selected="True">深圳</asp:ListItem>
                            <asp:ListItem Value="广州">广州</asp:ListItem>
                            <asp:ListItem Value="上海">上海</asp:ListItem>
                            <asp:ListItem Value="北京">北京</asp:ListItem>
                            <asp:ListItem Value="天津">天津</asp:ListItem>
                            <asp:ListItem Value="武汉">武汉</asp:ListItem>
                            <asp:ListItem Value="重庆">重庆</asp:ListItem>
                            <asp:ListItem Value="成都">成都</asp:ListItem>
                            <asp:ListItem Value="南京">南京</asp:ListItem>
                            <asp:ListItem Value="香港">香港</asp:ListItem>
                            <asp:ListItem Value="澳门">澳门</asp:ListItem>
                        </asp:dropdownlist></TD>
                    <TD><asp:button id="Button1" runat="server" Text="读取"></asp:button></TD>
                </TR>
                <TR>
                    <TD colSpan="3"><asp:label id="l_city" runat="server"></asp:label></TD>
                </TR>
                <TR>
                    <TD colSpan="3"><asp:label id="l_wea" runat="server"></asp:label></TD>
                </TR>
                <TR>
                    <TD colSpan="3"><asp:label id="l_sky" runat="server"></asp:label></TD>
                </TR>
                <TR>
                    <TD colSpan="3"><asp:label id="l_date" runat="server"></asp:label></TD>
                </TR>
                <TR>
                    <TD colSpan="3"><asp:label id="l_w1" runat="server"></asp:label></TD>
                </TR>
                <TR>
                    <TD colSpan="3"><asp:label id="l_w2" runat="server"></asp:label></TD>
                </TR>
                <TR>
                    <TD colSpan="3"><asp:label id="l_w3" runat="server"></asp:label></TD>
                </TR>
                <TR>
                    <TD colSpan="3"><asp:label id="l_w4" runat="server"></asp:label></TD>
                </TR>
            </TABLE>
        </form>
    </body>
</HTML>2.cs
添加如下应用
using System.Net;
using System.IO;页面代码
public class Weather : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Label l_date;
        protected System.Web.UI.WebControls.Label l_city;
        protected System.Web.UI.WebControls.Label l_wea;
        protected System.Web.UI.WebControls.Label l_sky;
        protected System.Web.UI.WebControls.Label l_w1;
        protected System.Web.UI.WebControls.Label l_w2;
        protected System.Web.UI.WebControls.Button Button1;
        protected System.Web.UI.WebControls.Label Label1;
        protected System.Web.UI.WebControls.Label l_w3;
        protected System.Web.UI.WebControls.Label l_w4;
        protected System.Web.UI.WebControls.DropDownList ddlcity;
   
        private void Page_Load(object sender, System.EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                writeWeatherInfo(ddlcity.SelectedValue);
                writeWeather(ddlcity.SelectedValue);
            }
        }   

        getWeatherByCity 通过城市过虑#region getWeatherByCity 通过城市过虑
        public string getWeatherByCity(string city)
        {
            string temp = null;
            try
            {
                string strURL = "http://weather.news.sina.com.cn/cgi-bin/figureWeather/search.cgi";
                HttpWebRequest request= (HttpWebRequest)WebRequest.Create(strURL);//使用 WebRequest.Create 方法初始化 HttpWebRequest 的一个新实例。如果 URI 的方案是 http:// 或 https://,则 Create 将返回 HttpWebRequest 实例。
                request.Method="POST"; //Post请求方式
                request.ContentType="application/x-www-form-urlencoded"; //内容类型
                string paraUrlCoded = System.Web.HttpUtility.UrlEncode("city"); //参数经过URL编码
                paraUrlCoded = paraUrlCoded + "=" + System.Web.HttpUtility.UrlEncode(city, System.Text.Encoding.GetEncoding("GB2312"));
                byte[] payload = System.Text.Encoding.GetEncoding("GB2312").GetBytes(paraUrlCoded); //将URL编码后的字符串转化为字节
                request.ContentLength = payload.Length; //设置请求的ContentLength
                Stream writer = request.GetRequestStream(); //获得请求流
                writer.Write(payload,0,payload.Length); //将请求参数写入流
                writer.Close(); //关闭请求流
                HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //获得响应流
                Stream s= response.GetResponseStream();
                StreamReader objReader = new StreamReader(s,System.Text.Encoding.GetEncoding("GB2312"));
                string HTML = "";
                string sLine = "";
                int i = 0;
                while (sLine!=null)
                {
                    i++;
                    sLine = objReader.ReadLine();
                    if (sLine!=null)
                        HTML += sLine;
                }
                HTML = HTML.Replace("&lt;","<");
                HTML = HTML.Replace("&gt;",">");
                int start,stop;
                //start = HTML.IndexOf("<img src=\"http://image2.sina.com.cn/dy/weather/images/figure/",0,HTML.Length);
                start = HTML.IndexOf("<table border=0 cellpadding=0 cellspacing=0 style=\"margin:5px;\">",0,HTML.Length);
                stop = HTML.IndexOf("<td background=http://image2.sina.com.cn/dy/weather/images",start);
                temp = HTML.Substring(start, stop - start);
            }
            catch (Exception x)
            {
            }
            return temp;
        }

        #endregion

        writeWeatherInfo 显示处理后的信息#region writeWeatherInfo 显示处理后的信息
        private void writeWeatherInfo(string city)
        {
            int start,stop;
            string weather1,weather2,wea;
            string wea_city = getWeatherByCity(city);

            wea_city = wea_city.Replace(" ","");

            start = wea_city.IndexOf("<b>",0,wea_city.Length);
            stop = wea_city.IndexOf("</b>", start);
            weather1 = wea_city.Substring(start, stop-start).Trim() + "          ";
            weather1 = weather1.Substring(3,8).Trim();
  
            start = wea_city.IndexOf("<tdstyle=\"font-size:40px;font-family:TimesNewRoman;font-weight:bold;\">",0,wea_city.Length);
            stop = wea_city.IndexOf("℃",start) + 40;
            weather2 = wea_city.Substring(start, stop-start);
            weather2 = weather2.Substring(stop-start-42,40).Trim();
            weather2 = weather2.Replace("\t","");

            start = wea_city.IndexOf("<fontcolor=#183888><b>", 0, wea_city.Length);
            stop = wea_city.IndexOf("</b></font>",start);
            wea = wea_city.Substring(start,stop-start);
            wea = wea.Substring(22,wea.Length-22) + "kbrk";
            wea = wea.Replace("\t", "");
            wea = wea.Replace(">", "k");
            wea = wea.Replace("<", "k");
            wea = wea.Replace("kbrk", "k");
            string [] wall = null;
            char[] seperator = {'k'};
            wall = wea.Split(seperator);

           
            l_city.Text = "[城市]:" + city;//城市
            l_wea.Text = "[天气]:" + weather1;//天气
            l_sky.Text = "[温度]:" + weather2;//温度
           
            l_date.Text = wall[0];//日期
            l_w1.Text = wall[1];//风向
            l_w2.Text = wall[2];//风力
            l_w3.Text = wall[3]; //空气质量
            l_w4.Text = wall[4]; //紫外线强度
        }
   
        #endregion

        writeWeather 直接显示读取到的信息#region writeWeather 直接显示读取到的信息
        private void writeWeather(string city)
        {
            string wea_city = getWeatherByCity(city);
            Response.Write(wea_city);
        }
        #endregion
   
        Button1_Click#region Button1_Click
        private void Button1_Click(object sender, System.EventArgs e)
        {
            writeWeatherInfo(ddlcity.SelectedValue);
            writeWeather(ddlcity.SelectedValue);
        }
        #endregion

        Web Form Designer generated code#region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }
       
        /**//// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {   
            this.Button1.Click += new System.EventHandler(this.Button1_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

       
    }

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zwei1121/archive/2006/04/10/657716.aspx

posted @ 2010-10-09 22:01  zhdonghu  阅读(237)  评论(0编辑  收藏  举报