本站业务范围:1、PC端软件开发、网站开发 2、移动端APP、网站、微信接口、微商城开发 3、视频教程、课程设计和辅导 4、单片机开发 5、串口通讯调试
 当前位置:文章中心 >> vs2022_vs2019_vs2017_vs2014_vs2012
立即购买视频教程 一个关于天气预报的WebService【C#版】
夜鹰教程网 来源:www.yyjcw.com 日期:2016-11-18 23:00:07
本文是借鉴天极网上的一片文章(SmartPhone手机上查看QQ天气预报)而改写的,本文的大部分代码是原文的,在原文的基出上做了改进(主要是针对GetWeatherDataSet(string cityName)做的修改),在原文中,所取出的数据都是包含HTML标记的,这样的数据放到网页上会破坏原有的排版,所以在文件加入函数解决了此问题;还有就是原文中就是每次访问Service都要到天气预报网页上取一次数据,这样造成了很大的资源浪费,所以在本地用Application做的缓存,只有当网页上数据日期过期时才会到网页上去收集新的信息。 

这篇文章不能解决你的问题?我们还有相关视频教程云课堂 全套前端开发工程师培训课程

微信号:yyjcw10000 QQ:1416759661  远程协助需要加QQ!

业务范围:视频教程|程序开发|在线解答|Demo制作|远程调试| 点击查看相关的视频教程

技术范围:全端开发/前端开发/webapp/web服务/接口开发/单片机/C#/java/node/sql server/mysql/mongodb/android/。 



本文是借鉴天极网上的一片文章(SmartPhone手机上查看QQ天气预报)而改写的,本文的大部分代码是原文的,在原文的基出上做了改进(主要是针对GetWeatherDataSet(string cityName)做的修改),在原文中,所取出的数据都是包含HTML标记的,这样的数据放到网页上会破坏原有的排版,所以在文件加入函数解决了此问题;还有就是原文中就是每次访问Service都要到天气预报网页上取一次数据,这样造成了很大的资源浪费,所以在本地用Application做的缓存,只有当网页上数据日期过期时才会到网页上去收集新的信息。

    本文所用到的组件(Binken.Platform.General_Function)可以到 一个常用的Asp.Net常用函数库去下载,网上很多,随便百度下都能搜索到,这里我就不给地址了。

1、建立一个名为WeatherService的WebService,并将QQ的天气服务转为XML WebService服务,部署在一台具有固定IP的服务器上。

2、新建一个WeatherDataSet.XSD,存储天气信息

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema id="WeatherDataSet"
                  targetNamespace="Sailong.Services.WeatherService"
                  elementFormDefault="qualified"
                  attributeFormDefault="qualified"
                  xmlns="Sailong.Services.WeatherService"
                  xmlns:mstns="Sailong.Services.WeatherService"
                  xmlns:xs="http://www.w3.org/2001/XMLSchema"
                  xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="WeatherDataSet" msdata:IsDataSet="true">
<xs:complexType>
      <xs:choice maxOccurs="unbounded">
      <xs:element name="WeatherDS">
      <xs:complexType>
   <xs:sequence>
       <xs:element name="CityName" type="xs:string" minOccurs="0" ></xs:element>
       <xs:element name="Date1" type="xs:string" minOccurs="0" ></xs:element>
       <xs:element name="Weather1" type="xs:string" minOccurs="0" ></xs:element>
       <xs:element name="Temp1" type="xs:string" minOccurs="0" ></xs:element>
       <xs:element name="WindPower1" type="xs:string" minOccurs="0" ></xs:element>
       <xs:element name="Date2" type="xs:string" minOccurs="0" ></xs:element>
       <xs:element name="Weather2" type="xs:string" minOccurs="0" ></xs:element>
       <xs:element name="Temp2" type="xs:string" minOccurs="0" ></xs:element>
       <xs:element name="WindPower2" type="xs:string" minOccurs="0" ></xs:element>
    </xs:sequence>
    </xs:complexType>
    </xs:element>
    </xs:choice>
   </xs:complexType>
   </xs:element>
</xs:schema>


3、WeatherService的源代码如下

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Net;
using System.Text;
using Binken.Platform.General_Function;


namespace WeatherService
{
    [WebService(Description="WeatherService 天气Service",Namespace="WeatherService")]
    /// <summary>
    /// 天气预报Service
    /// </summary>
    public class Weather : System.Web.Services.WebService
    {
        #region Variable
        private string tommorow;
        #endregion

        #region 构造函数
        public Weather ()
        {
            //CODEGEN: 该调用是 ASP.NET Web 服务设计器所必需的
            InitializeComponent();
        }
        #endregion

        #region 组件设计器生成的代码
       
        //Web 服务设计器所必需的
        private IContainer components = null;
               
        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
        }

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if(disposing && components != null)
            {
                components.Dispose();
            }
            base.Dispose(disposing);       
        }
       
        #endregion

        #region GetWeatherDataSet 天气预报

        [WebMethod(Description="天气预报(DataSet)")]
        public DataSet GetWeatherDataSet(string cityName)
        {
            string url=@"http://appnews.qq.com/cgi-bin/news_qq_search";
            string weatherData="";
            //DataSet ds = new DataSet ();
            try
            {
                WeatherDataSet weatherDs = new WeatherDataSet();

                if(Application ["Weather"] != null)
                {
                    weatherDs = (WeatherDataSet)Application ["Weather"];
                    string w = weatherDs.Tables[0].Rows [0]["Date1"].ToString();
                   
                    if(DateTime.Parse (w).Date != DateTime.Today.Date )
                    {
                        weatherDs.Clear ();
                        weatherData = GetPage(url,cityName).Replace(" ","").Trim();
                        weatherDs.WeatherDS.AddWeatherDSRow(GetWeatherRow(ref weatherDs, weatherData, cityName) );
                        Application ["Weather"] = weatherDs;
                    }
                }
                else
                {
                    weatherDs.Clear ();
                    weatherData = GetPage(url,cityName).Replace(" ","").Trim();
                    weatherDs.WeatherDS.AddWeatherDSRow(GetWeatherRow(ref weatherDs, weatherData, cityName) );
                    Application ["Weather"] = weatherDs;
                }
                return weatherDs;

            }
            catch(Exception err)
            {
                throw new Exception("对不起,没有这个城市的天气信息!"+ err.ToString ());
            }
           
        }
       
        private WeatherDataSet.WeatherDSRow GetWeatherRow(ref WeatherDataSet weatherDs, string weatherData, string cityName)
        {
            try
            {
                Common_Function cf = new Common_Function ();
                WeatherDataSet.WeatherDSRow weatherRow = weatherDs.WeatherDS.NewWeatherDSRow();
                weatherRow.CityName = cityName ;
                weatherRow.Date1 = cf.Text_Remove_WebTag (weatherData.Substring(weatherData.IndexOf(cityName)+ cityName.Length, weatherData.IndexOf("天气")-(weatherData.IndexOf(cityName) + cityName.Length))).Replace (" " , "");
                //计算明日日期
                if(DateTime.Parse (weatherRow.Date1).AddDays(1).Month.ToString().Length == 1)
                {
                    tommorow= "0" + DateTime.Parse (weatherRow.Date1).AddDays(1).Month.ToString()+"月" + DateTime.Parse (weatherRow.Date1).AddDays(1).Day.ToString()+"日";
                }
                else
                {
                    tommorow= DateTime.Parse (weatherRow.Date1).AddDays(1).Month.ToString()+"月" + DateTime.Parse (weatherRow.Date1).AddDays(1).Day.ToString()+"日";
                }

                weatherRow.Weather1 = cf.Text_Remove_WebTag (weatherData.Substring(weatherData.IndexOf("天气")+"天气".Length, weatherData.IndexOf("气温")-(weatherData.IndexOf("天气")+"天气".Length)));
                weatherRow.Temp1 = cf.Text_Remove_WebTag (weatherData.Substring(weatherData.IndexOf("气温")+"气温".Length,weatherData.IndexOf("风力")-(weatherData.IndexOf("气温")+"气温".Length)).Replace("℃-","℃/"));
                weatherRow.WindPower1 = cf.Text_Remove_WebTag (weatherData.Substring(weatherData.IndexOf("风力")+"风力".Length,weatherData.IndexOf(tommorow)-(weatherData.IndexOf("风力")+"风力".Length)));
                weatherRow.Date2 = tommorow;
                weatherRow.Weather2 = cf.Text_Remove_WebTag (weatherData.Substring(weatherData.LastIndexOf("天气")+"天气".Length,weatherData.LastIndexOf("气温")-(weatherData.LastIndexOf("天气")+"天气".Length)));
                weatherRow.Temp2 = cf.Text_Remove_WebTag (weatherData.Substring(weatherData.LastIndexOf("气温")+"气温".Length,weatherData.LastIndexOf("风力")-(weatherData.LastIndexOf("气温")+"气温".Length)).Replace("℃-","℃/"));
                weatherRow.WindPower2 = cf.Text_Remove_WebTag (weatherData.Substring(weatherData.LastIndexOf("风力")+"风力".Length));
                return weatherRow;
            }
            catch(Exception err)
            {
                throw new Exception (err.ToString ());
            }
        }
       
        #endregion
       
        #region GetPageString 获取QQ的天气服务
       
        //private string xx="";
       
        [WebMethod(Description="天气预报(WebPage)")]
        public string GetPageString(string cityName)
        {
            string url=@"http://appnews.qq.com/cgi-bin/news_qq_search";
            return GetPage(url,cityName);
        }
       
        /// <summary>
        /// 从QQ上获取天气详细信息
        /// </summary>
        /// <param name="url">QQ气像链接</param>
        /// <param name="cityName">城市名称</param>
        /// <returns>string</returns>
        private static string GetPage(string url,string cityName)
        {
            HttpWebResponse res = null;
            string strResult = "";
            try
            {
                string postData = "city=" + HttpUtility.UrlEncode(cityName,System.Text.Encoding.GetEncoding("GB2312"));
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.KeepAlive = true;
                req.ContentType = "application/x-www-form-urlencoded";
                StringBuilder UrlEncoded = new StringBuilder();
                byte[] SomeBytes = Encoding.ASCII.GetBytes(postData);
                req.ContentLength = SomeBytes.Length;
                Stream newStream = req.GetRequestStream();
                newStream.Write(SomeBytes, 0, SomeBytes.Length);
                newStream.Close();
               
                //获得流内容
                res = (HttpWebResponse)req.GetResponse();
                System.IO.Stream s = res.GetResponseStream();
                StreamReader reader = new StreamReader(s,System.Text.Encoding.Default);
                strResult = reader.ReadToEnd();
            }
            catch(Exception e)
            {
                strResult = e.ToString();
            }
            finally
            {
                if ( res != null )
                {
                    res.Close();
                }
            }
           
            strResult=strResult.Remove(0,strResult.IndexOf("●"));
            if( cityName != "北京" )
            {
                strResult=strResult.Remove(strResult.IndexOf("北京"),strResult.Length-strResult.IndexOf("北京"));
            }
            else
            {
                strResult=strResult.Remove(strResult.LastIndexOf("北京"),strResult.Length-strResult.LastIndexOf("北京"));
            }
           
            strResult=strResult.Trim();
            while(strResult.IndexOf(@"<") != -1)
            {
                strResult=strResult.Remove(strResult.IndexOf(@"<"),strResult.IndexOf(@">")-strResult.IndexOf(@"<")+1);
            }
            while(strResult.IndexOf(@" ") != -1)
            {
                strResult=strResult.Replace(" ","");
            }
            string x = Encoding.UTF8.GetString(new Byte[]{10});
            string y = Encoding.UTF8.GetString(new Byte[]{9});
            while(strResult.IndexOf(x) != -1)
            {
                strResult=strResult.Replace(x,"");
            }
            while(strResult.IndexOf(y) != -1)
            {
                strResult=strResult.Replace(y,"");
            }
            return strResult;
        }
       
        #endregion
    }
}

4、记得在Web.Config文件加入以下节点,使得WebService能被外部访问

<!-- WebService 获取的途径 -->
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
<add name="HttpPostLocalhost"/?
<add name="Documentation"/>
</protocols>
</webServices>

OK,编译后架到服务器上,就可以用客户端实时获取气象数据了,也可以在SmartPhone手机上查看天气预报,本文所取的数据是QQ上的数据,当然您也可以用其它网页上的数据。

复制链接 网友评论 收藏本文 关闭此页
上一条: 如何动态写入服务器端控件--ASP.N…  下一条: WebService究竟是什么
夜鹰教程网成立于2008年,目前已经运营了将近 13 年,发布了大量关于 html5/css3/C#/asp.net/java/python/nodejs/mongodb/sql server/android/javascript/mysql/mvc/easyui/vue/echarts原创教程。 我们一直都在坚持的是:认证负责、一丝不苟、以工匠的精神来打磨每一套教程,让读者感受到作者的用心。我们默默投入的时间,确保每一套教程都是一件作品,而不是呆板的文字和视频! 目前我们推出在线辅导班试运营,模式为一对一辅导,教学工具为QQ。我们的辅导学科包括 java 、android原生开发、webapp开发、商城开发、C#和asp.net开发,winform和物联网开发、web前端开发,但不仅限于此。 普通班针对的是国内学员,例如想打好基础的大学生、想转行的有志青年、想深入学习的程序员、想开发软件的初学者或者业余爱好者等。 就业办针对即将毕业上岗的大四学生,或者打算转行的初级开发工程师。 留学生班针对的是在欧美、加拿大、澳洲、日本、韩国、新加坡等地留学的中国学子,目的是让大家熟练地掌握编程技能,按时完成老师布置的作业,并能顺利地通过考试。 详细咨询QQ:1416759661   夜鹰教程网  基于角色的权限管理系统(c-s/b-s)。
  夜鹰教程网  基于nodejs的聊天室开发视频教程
  夜鹰教程网  Git分布式版本管理视频教程
  夜鹰教程网  MVC+EasyUI视频教程
  夜鹰教程网  在线考试系统视频教程
  夜鹰教程网  MongoDB视频教程。
  夜鹰教程网 Canvas视频教程
  夜鹰教程网 报表开发视频教程
  推荐教程/优惠活动

  热门服务/教程目录

  夜鹰教程网  新手必看,详细又全面。
  夜鹰教程网  购买教程  夜鹰教程网  在线支付-方便
  夜鹰教程网  担保交易-快捷安全   夜鹰教程网  闪电发货
  夜鹰教程网  电话和QQ随时可以联系我们。
  夜鹰教程网 不会的功能都可以找我们,按工作量收费。

客服电话:153 9760 0032

购买教程QQ:1416759661  
  热点推荐
一个关于天气预报的WebService【C…
VS2010最大的新特点是并行编程的进…
TextBox控件:asp.net中如何为密码…
Web服务调用实例:实现天气预报的…
ASP.NET程序员面试试题(130道题)
ASP.NET教程:调用WebService的源码…
网站开发全程设计
据说这套.net面试题很多网络公司都…
考考你:C#常见题型及部分答案
原创:.net读取数据库sql2000
伪静态URL重写配置
配置web.config代码asp.net3.5个性…
使用线程池提高性能 Socket网络编…
ASP.NET(C#)GridView表头的增加…
如何找到正确的学习方向【.NET版】…
  尊贵服务
夜鹰教程网 承接业务:软件开发 网站开发 网页设计 .Net+C#+VS2008+MSsql+Jquery+ExtJs全套高清完整版视频教程
  最近更新
C#修改注册表demo
一个获取内容中的图片地址的方法
ASP.NET 4.0尚未在 Web 服务器上注…
四大作用域:application,session…
ConfigurationManager不存在的解决…
vs2012_vs2013_vs2015没有Web Dep…
vs2015禁用解决方案中单击打开文件…
微软为Visual Studio 2015新增安卓…
C#如何实现搜索引擎网络爬虫程序
C#中正则表达式的用法
用C#抓取需要登录的页面数据
VS2015新功能
VS2015安装图解教程
vs2015新功能介绍
vs2015安装图解
  工具下载  需要远程协助? 

sql2008视频教程 c#视频教程

VIP服务:如果您的某个功能不会做,可以加我们QQ,给你做DEMO!

JQUERY  Asp.net教程

MVC视频教程  vs2012
.NET+sql开发
手机:15397600032 C#视频教程下载
微信小程序 vue.js高级实例视频教程

教程咨询QQ:1416759661


这篇文章不能解决你的问题?我们还有相关视频教程云课堂 全套前端开发工程师培训课程

微信号:yyjcw10000 QQ:1416759661  远程协助需要加QQ!

业务范围:视频教程|程序开发|在线解答|Demo制作|远程调试| 点击查看相关的视频教程

技术范围:全端开发/前端开发/webapp/web服务/接口开发/单片机/C#/java/node/sql server/mysql/mongodb/android/。 



关于我们 | 购买教程 | 网站建设 | 技术辅导 | 常见问题 | 联系我们 | 友情链接

夜鹰教程网 版权所有 www.yyjcw.com All rights reserved 备案号:蜀ICP备08011740号3