内网公告牌获取天气信息解决方案(C# WebForm)
需求:内网公告牌能够正确显示未来三天的天气信息
本文关键字: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 + ")");
} }
}
内网公告牌获取天气信息解决方案(C# WebForm)的更多相关文章
- C#调用WebService获取天气信息
		
概述 本文使用C#开发Winform应用程序,通过调用<WebXml/>(URL:http://www.webxml.com.cn)的WebService服务WeatherWS来获取天气预 ...
 - Java通过webservice接口获取天气信息
		
通过SOAP请求的方式获取天气信息并解析返回的XML文件. 参考: http://www.webxml.com.cn/WebServices/WeatherWS.asmx import java.io ...
 - ESP32 IDF 获取天气信息
		
一.注册天气获取账号 我使用的知心天气,没有获取天气账号的小伙伴可以去注册一下,知心天气官网:https://www.seniverse.com/ 取得天气获取的API后,可以直接在浏览器中访问测试一 ...
 - 半吊子学习Swift--天气预报程序-获取天气信息
		
昨天申请的彩云天气Api开发者今天上午已审核通过  饭后运动过后就马不停蹄的来测试接口,接口是采用经纬度的方式来获取天气信息,接口地址如下 https://api.caiyunapp.com/v2/ ...
 - java获取天气信息
		
通过天气信息接口获取天气信息,首先要给项目导入程序所需要的包,具体需要如下几个包: json-lib-2.4.jar ezmorph-1.0.6.jar commons-beanutils-1.8.3 ...
 - Kettle通过Webservice获取天气信息
		
Kettle通过Webservice获取天气信息 需求: 通过kettle工具,通过webservice获取天气信息,写成xml格式文件. 思路: Kettle可通过两种选择获取webservic ...
 - ajax无刷新获取天气信息
		
浏览器由于安全方面的问题,禁止ajax跨域请求其他网站的数据,但是可以再本地的服务器上获取其他服务器的信息,在通过ajax请求本地服务来实现: <?php header("conten ...
 - Android实现自动定位城市并获取天气信息
		
定位实现代码: <span style="font-size:14px;">import java.io.IOException; import java.util.L ...
 - java解析xml实例——获取天气信息
		
获取xml并解析其中的数据: package getweather.xml; import java.io.IOException; import java.util.HashMap; import ...
 
随机推荐
- WordPress登陆页和后台面空白解决方法
			
真没想到我居然也会碰到这么蛋疼的事情,有一天我登陆博客,输入账号密码之后登陆没有反应,之后我就试着用首页前台登陆(因为这个模板前台带登陆功能),之后成功登陆进入后台更新文章.我想算了.这小毛病就丢那吧 ...
 - Winform 文本框多线程赋值
			
delegate void SetTextCallback(string text); private void showClientMsg(string text) { // InvokeRequi ...
 - 2015-01-16 .Net 中级软件工程师 笔试题
			
一 C#方面 1.请简述多线程需要考虑的主要因素 答:1.线程管理 同一核上的两个线程不会以两倍的时长完成,可能需要用两倍再加10 %左右的时间来完成.与一个线程相比较的话,三个线程在同一核上想占用1 ...
 - uva 10271 (dp)
			
题意:有n个数据,给定k,要从中选出k+8个三元组(x,y,z,其中x<=y<=z),每选一次的代价为(x-y)^2,求最小代价和. [解题方法] 将筷子按长度从大到小排序 排序原因: 由 ...
 - WEB安全性测试
			
SQL注入 所谓SQL注入,就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令.具体来说,它是利用现有应用程序,将(恶意)的SQL命令 ...
 - java 将数据写进文件
			
/*每次只写入一行数据 只需要调用特定的方法即可.*/package com.second.File;import java.io.*;/** * Created by hasee on 2016/1 ...
 - 使用R进行地图相关的可视化
			
Here is a solution using the geosphere and maps package. Using the gcIntermediate function you can & ...
 - CocoaPods安装流程
			
iOS 最新版 CocoaPods 的安装流程 1.移除现有Ruby默认源 $gem sources --remove https://rubygems.org/ 2.使用新的源 $g ...
 - TEA(Tiny Encryption Algorithm)
			
简介 TEA是一种简单高效的加解密算法,以速度快,实现简单著称.TEA算法每一次可以操作64-bit数据,采用128-bit作为key,算法采用迭代的形式,推荐的迭代轮数是64,最少32. 代码(默认 ...
 - RAM清理器
			
或许有些氨基小白不知道RAM是什么,官方的解释是"运行内存" 只要你的RAM够大,你玩什么都不卡! 今天给大家带来的就是 <RAM清理器>!!体积小,能量大就是我给他介 ...