初试牛刀:实时天气WebService

时间:2021-07-27 23:00:16

1.引入WebService:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

2.声明接口→界面获取值传入接口→接口返回值处理→输入

public string sWeatherHTML = "";
        protected void Button1_Click(object sender, EventArgs e)
        {
            string txtCity=TextBox1.Text;
            cn.com.webxml.www.WeatherWebService ws = new cn.com.webxml.www.WeatherWebService();
            string[] aWeather = ws.getWeatherbyCityName(txtCity);

            StringBuilder sb=new StringBuilder();
            sb.Append("<table>");
            sb.Append(string.Format("<tr><td>城市:</td><td>{0}</td></tr>",aWeather[1].ToString()));
            sb.Append(string.Format("<tr><td>温度:</td><td>{0}</td></tr>", aWeather[5].ToString()));
            sb.Append(string.Format("<tr><td>气候:</td><td>{0}</td></tr>", aWeather[6].ToString()));
        
            if(aWeather[8].ToString()==aWeather[9].ToString())
            {
                //转义:前面加@,双  双引号
                sb.Append(string.Format(@"<tr><td>气候:</td><td><img src=""weather/a_{0}""></td></tr>", aWeather[6].ToString()));
            }
            else
            {
                sb.Append(string.Format(@"<tr><td>气候:</td><td><img src=""weather/a_{0}"">转<img src=""weather/a_{1}""></td></tr>", aWeather[8].ToString(), aWeather[9].ToString()));
            }
            sb.Append(string.Format("<tr><td>详情:</td><td>{0}</td></tr>", aWeather[10].ToString()));
            sb.Append("</table>");
            sWeatherHTML = sb.ToString();
        }

3.界面显示处理

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
  
    <div>
        <%=sWeatherHTML %>
    </div>
    </form>
</body>