内网公告牌获取天气信息解决方案(C# WebForm)

Posted on 2016-07-07 12:17  MR.DByang  阅读(493)  评论(0)    收藏  举报

需求:内网公告牌能够正确显示未来三天的天气信息

本文关键字:C#/WebForm/Web定时任务/Ajax跨域

规划:

1、天定时读取百度接口获取天气信息并存储至Txt文档;

2、示牌开启时请求WebService,获取天气信息;

解决方案:

1、在Global.asax中能够配置整个工程不同情况下触发的事件,其中 Application_Start方法是在iis启动本项目时就开始的进程。在本方法下写入定时从百度读取天气信息的代码,调用的WebService代码在下面的第2部分:

  

protected void Application_Start(object sender, EventArgs e)
        {
            String NowTime = DateTime.Now.ToString("hh24:mi:ss");
            //定时任务
            //if (NowTime == "")
            //{
            WebService1 ws = new WebService1();
            ws.GetBaiduWeather();
            //}
            //每天执行一次
            Timer t = new Timer(60 * 60 * 24 * 1000);
            t.Elapsed += new System.Timers.ElapsedEventHandler(DownLoadWeather);
            t.Enabled = true;

        }

   WebService代码如下

[WebMethod]
        public void GetBaiduWeather()
        {
            string callback = HttpContext.Current.Request["jsoncallback"];
            WeatherDownload.getrequest();
            HttpContext.Current.Response.Write(callback +
                "({result:'true'})");
            HttpContext.Current.Response.End();
        }

 

  调用百度天气接口存储数据的代码如下所示,其存储的结果是Json字符串。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace WebService
{
    public static class WeatherDownload
    {
        public static string url = "http://apis.baidu.com/apistore/weatherservice/recentweathers";
        public static string param = "cityname=石家庄&cityid=101090101";
        /// <summary>
        /// 查询天气情况
        /// </summary>
        /// <param name="url"></param>
        public static void getrequest()
        {
            string strURL = url + '?' + param;
            System.Net.HttpWebRequest request;
            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            request.Method = "GET";
            request.Headers.Add("apikey", "在百度上申请的开发者个人码");
            System.Net.HttpWebResponse response;
            response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.Stream s;
            s = response.GetResponseStream();
            string StrDate = "";
            string strValue = "";
            StreamReader Reader = new StreamReader(s, Encoding.UTF8);
            while ((StrDate = Reader.ReadLine()) != null)
            {
                strValue += StrDate + "\r\n";
            }
            if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt"))
            {
            }
            else
            {
                using (File.Create(System.AppDomain.CurrentDomain.BaseDirectory + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt"))
                {
                }
            }
            FileStream fs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            String w = UnicodeToStr(strValue);
            sw.Write(w);
            sw.Flush();
            sw.Close();
            fs.Close();
        }
        /// <summary>
        /// 编码为汉字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UnicodeToStr(string str)
        {
            string outStr = "";
            Regex reg = new Regex(@"(?i)\\u([0-9a-f]{4})");
            outStr = reg.Replace(str, delegate(Match m1)
            {
                return ((char)Convert.ToInt32(m1.Groups[1].Value, 16)).ToString();
            });
            return outStr;
        }
    }
}

 2、页面请求WebService获取天气数据

  此处使用的Ajax请求,特征是跨域请求,当时出的问题比较多,一篇很好的参考文献如下(http://www@suchso@com/projecteactual/jquery-ajax-parsererror-was-not-called.html)(请把@改为.)

$.ajax({
        //111.111.111.111为实际 url: "http://111.111.111.111/WebService1.asmx/GetWeather?jsoncallback=?", dataType: "jsonp", success: OnSuccess, error: OnError }); //} function OnSuccess(json) { $("#today").text(json.retData.today.curTemp.toString()) $("#today_wth").text(json.retData.today.type.toString()) } function OnError(XMLHttpRequest, textStatus, errorThrown) { alert("Something error"); }

   对应的WebService代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Text;
namespace WebService
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public void GetWeather()
        {
            String sr = File.ReadAllText(System.AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("yyyyMMdd") + ".txt", UnicodeEncoding.GetEncoding("UTF-8"));
            
            string callback = HttpContext.Current.Request["jsoncallback"];
            HttpContext.Current.Response.Write(callback + "(" + sr + ")");
        }

    }
}