.net请求Webservice简单实现天气预报功能
1.新建一个网站或者web应用程序,添加一个aspx页面,用于展示天气数据。(这个应该不用细讲吧)
2.在网上找一个免费的天气预报的接口,我用的是Webxml网站的,地址如下:
http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx
3.在项目目录下, 引用 — 添加服务引用,弹出对话框,然后输入接口地址,点击前往,命名空间可以改成你想要的,如下图:
一般处理程序代码如下:
using System.Web; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; namespace WeatherTest.ashx { /// <summary> /// weatherHandler 的摘要说明 /// </summary> public class weatherHandler : IHttpHandler { WeatherWsClient.WeatherWSSoapClient client = new WeatherWsClient.WeatherWSSoapClient(); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string[] result = null; string option = context.Request.Form["option"]; switch (option) { case "province": result = GetProvinces(); break; case "city": result = GetCitys(context.Request.Form["provinceid"]); break; case "weather": result = GetWeather(context.Request.Form["cityid"], null); break; } string str = ConvertToString(result, option); context.Response.Write(str); } /// <summary> /// 数组转字符串 /// </summary> /// <param name="result"></param> /// <param name="option"></param> /// <returns></returns> private string ConvertToString(string[] result, string option) { StringBuilder sb = new StringBuilder(); foreach (string item in result) { sb.Append(item+"|"); } return sb.ToString(); } /// <summary> /// 省份 /// </summary> /// <returns></returns> private string[] GetProvinces() { return client.getRegionProvince(); } /// <summary> /// 城市 /// </summary> /// <param name="provinceid"></param> /// <returns></returns> private string[] GetCitys(string provinceid) { return client.getSupportCityString(provinceid); } /// <summary> /// 天气数据 /// </summary> /// <param name="cityid"></param> /// <param name="userid"></param> /// <returns></returns> private string[] GetWeather(string cityid, string userid) { return client.getWeather(cityid, userid); } public bool IsReusable { get { return false; } } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。