Flash与ASP.NET结合实现天气预报功能总结
Flash与ASP.NET结合实现天气预报功能总结
方便起见在百度空间也写了一份。
http://hi.baidu.com/guosq/blog/item/709d8df81e927fc2b58f310a.html
第一步:编写ASP.NET代码,获取天气预报数据(JSON),处理成Flash可识别的格式并写入w.txt,供flash调用。
1. Weather.aspx.cs

using System;
using System.Configuration;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
namespace web
{
public partial class Weather : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Response.ContentType = "application/json";
//Response.ContentType = "application/unicode";
string cityid = ConfigurationManager.AppSettings["weather_cityid"].ToString();
//101090501 = 唐山
/*
* 唐山:101090501
根据 下面的接口可获得城市天气情况
http://www.weather.com.cn/data/sk/101090501.html
* {"weatherinfo":{"city":"北京","cityid":"101010100","temp":"10","WD":"西风","WS":"2级","SD":"59%","WSE":"2","time":"11:20","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB"}}
*
*
http://www.weather.com.cn/data/cityinfo/101010100.html
* {"weatherinfo":{"city":"北京","cityid":"101010100","temp1":"13℃","temp2":"5℃","weather":"小雨转阴","img1":"d7.gif","img2":"n2.gif","ptime":"11:00"}}
*
*
http://m.weather.com.cn/data/101010100.html
* {"weatherinfo":{"city":"北京","city_en":"beijing","date_y":"2011年10月26日","date":"辛卯年","week":"星期三","fchh":"11","cityid":"101010100","temp1":"13℃~5℃","temp2":"17℃~4℃","temp3":"17℃~6℃","temp4":"17℃~6℃","temp5":"18℃~7℃","temp6":"17℃~8℃","tempF1":"55.4℉~41℉","tempF2":"62.6℉~39.2℉","tempF3":"62.6℉~42.8℉","tempF4":"62.6℉~42.8℉","tempF5":"64.4℉~44.6℉","tempF6":"62.6℉~46.4℉","weather1":"小雨转阴","weather2":"多云转晴","weather3":"晴转多云","weather4":"多云转晴","weather5":"晴转多云","weather6":"多云","img1":"7","img2":"2","img3":"1","img4":"0","img5":"0","img6":"1","img7":"1","img8":"0","img9":"0","img10":"1","img11":"1","img12":"99","img_single":"7","img_title1":"小雨","img_title2":"阴","img_title3":"多云","img_title4":"晴","img_title5":"晴","img_title6":"多云","img_title7":"多云","img_title8":"晴","img_title9":"晴","img_title10":"多云","img_title11":"多云","img_title12":"多云","img_title_single":"小雨","wind1":"微风","wind2":"微风","wind3":"微风","wind4":"微风","wind5":"微风","wind6":"微风","fx1":"微风","fx2":"微风","fl1":"小于3级","fl2":"小于3级","fl3":"小于3级","fl4":"小于3级","fl5":"小于3级","fl6":"小于3级","index":"舒适","index_d":"建议着薄型套装或牛仔衫裤等春秋过渡装。年老体弱者宜着套装、夹克衫等。","index48":"温凉","index48_d":"较凉爽,建议着夹衣加薄羊毛衫等春秋服装。体弱者宜着夹衣加羊毛衫。因昼夜温差较大,注意增减衣服。","index_uv":"最弱","index48_uv":"弱","index_xc":"不宜","index_tr":"适宜","index_co":"较舒适","st1":"11","st2":"5","st3":"17","st4":"6","st5":"17","st6":"6","index_cl":"较不宜","index_ls":"不宜","index_ag":"不易发"}}
*
*
*/
string url = "http://www.weather.com.cn/data/cityinfo/" + cityid + ".html";
//返回数据:{"weatherinfo":{"city":"唐山","cityid":"101090501","temp1":"15℃","temp2":"5℃","weather":"晴转阴","img1":"d0.gif","img2":"n2.gif","ptime":"08:00"}}
//http://www.weather.com.cn/data/sk/101090501.html
string url1 = "http://www.weather.com.cn/data/sk/" + cityid + ".html";
//返回数据:{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"10","WD":"西风","WS":"2级","SD":"59%","WSE":"2","time":"11:20","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB"}}
//System.Net.HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
string data = GetRequestString(url, 8000, 1, Encoding.UTF8);
//string arr = data.Split(':');
CommonJsonModel model = DeSerialize(data);
string weather = model.GetModel("weatherinfo").GetValue("weather");// return 晴转阴
string temp = model.GetModel("weatherinfo").GetValue("temp1") +"到"+ model.GetModel("weatherinfo").GetValue("temp2");// return 15℃ - 5℃
string data1 = GetRequestString(url1, 8000, 1, Encoding.UTF8);
CommonJsonModel model1 = DeSerialize(data1);
string wind = model1.GetModel("weatherinfo").GetValue("WD") +" " + model1.GetModel("weatherinfo").GetValue("WS");// return 西风 2级
//2. {"total":0,"data":{"377149574" : 1}}
//CommonJsonModel model = DeSerialize(json);
//model.GetModel("data").GetValue("377149574") //return 1
//Response.Write(weather+"|"+temp+"|"+wind);
//weather=晴转阴&temp=14℃到5℃&wind=西南风 2级
//weather = Server.UrlEncode(weather);
//temp = Server.UrlEncode(temp);
//wind = Server.UrlEncode(wind);
string result = "weather=" + weather + "&temp=" + temp + "&wind=" + wind;
//result = Server.UrlEncode(result);
//写入txt,txt文档在Flash中调用
string txtFilePath = Server.MapPath("w.txt");
StreamWriter swr = new StreamWriter(txtFilePath,false,Encoding.UTF8);
swr.Write(result);
swr.Close();
swr.Dispose();
Response.Write(result);
Response.End();
}
public CommonJsonModel DeSerialize(string json)
{
return new CommonJsonModel(json);
}
#region 获取指定远程网页内容
/// <summary>
/// 获取指定远程网页内容
/// </summary>
/// <param name="strUrl">所要查找的远程网页地址</param>
/// <param name="timeout">超时时长设置,一般设置为8000</param>
/// <param name="enterType">是否输出换行符,0不输出,1输出文本框换行</param>
/// <param name="EnCodeType">编码方式</param>
/// <returns></returns>
/// 也可考虑 static string
public string GetRequestString(string strUrl, int timeout, int enterType, Encoding EnCodeType)
{
string strResult;
try
{
HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
myReq.Timeout = timeout;
HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
Stream myStream = HttpWResp.GetResponseStream();
StreamReader sr = new StreamReader(myStream, EnCodeType);
StringBuilder strBuilder = new StringBuilder();
while (-1 != sr.Peek())
{
strBuilder.Append(sr.ReadLine());
if (enterType == 1)
{
strBuilder.Append("\r\n");
}
}
strResult = strBuilder.ToString();
}
catch (Exception err)
{
strResult = "请求错误:" + err.Message;
}
return strResult;
}
#endregion
}
}
2. 获取JSON后,需要编写解析JSON的代码,此处新建了两个类clsJson.cs和CommonJsonModel.cs。
clsJson.cs 代码:

using System;
using System.Collections.Generic;
using System.Text;
namespace web
{
public class clsJson
{
protected string _GetKey(string rawjson)
{
if (string.IsNullOrEmpty(rawjson))
return rawjson;
rawjson = rawjson.Trim();
string[] jsons = rawjson.Split(new char[] { ':' });
if (jsons.Length < 2)
return rawjson;
return jsons[0].Replace("\"", "").Trim();
}
protected string _GetValue(string rawjson)
{
if (string.IsNullOrEmpty(rawjson))
return rawjson;
rawjson = rawjson.Trim();
string[] jsons = rawjson.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
if (jsons.Length < 2)
return rawjson;
StringBuilder builder = new StringBuilder();
for (int i = 1; i < jsons.Length; i++)
{
builder.Append(jsons[i]);
builder.Append(":");
}
if (builder.Length > 0)
builder.Remove(builder.Length - 1, 1);
string value = builder.ToString();
if (value.StartsWith("\""))
value = value.Substring(1);
if (value.EndsWith("\""))
value = value.Substring(0, value.Length - 1);
return value;
}
protected List<string> _GetCollection(string rawjson)
{
//[{},{}]
List<string> list = new List<string>();
if (string.IsNullOrEmpty(rawjson))
return list;
rawjson = rawjson.Trim();
StringBuilder builder = new StringBuilder();
int nestlevel = -1;
int mnestlevel = -1;
for (int i = 0; i < rawjson.Length; i++)
{
if (i == 0)
continue;
else if (i == rawjson.Length - 1)
continue;
char jsonchar = rawjson[i];
if (jsonchar == '{')
{
nestlevel++;
}
if (jsonchar == '}')
{
nestlevel--;
}
if (jsonchar == '[')
{
mnestlevel++;
}
if (jsonchar == ']')
{
mnestlevel--;
}
if (jsonchar == ',' && nestlevel == -1 && mnestlevel == -1)
{
list.Add(builder.ToString());
builder = new StringBuilder();
}
else
{
builder.Append(jsonchar);
}
}
if (builder.Length > 0)
list.Add(builder.ToString());
return list;
}
}
}
CommonJsonModel.cs 代码:

using System;
using System.Collections.Generic;
using System.Text;
/*
使用方法
public CommonJsonModel DeSerialize(string json)
{
return new CommonJsonModel(json);
}
超级简单,只要new一个通用对象,把json字符串放进去就行了。
针对上文的3个例子,我给出3种使用方法:
*
1. {"total":0}
CommonJsonModel model = DeSerialize(json);
model.GetValue("total") // return 0
2. {"total":0,"data":{"377149574" : 1}}
CommonJsonModel model = DeSerialize(json);
model.GetModel("data").GetValue("377149574") //return 1
3. {"total":0,"data":{"377149574":[{"cid":"377149574"}]}}
CommonJsonModel model = DeSerialize(json);
model.GetCollection("377149574").GetCollection()[0].GetValue("cid") //return 377149574
这个有点点复杂,
1. 首先377149574代表了一个集合,所以要用model.GetCollection("377149574")把这个集合取出来。
2. 其次这个集合里面包含了很多对象,因此用GetColllection()把这些对象取出来
3. 在这些对象List里面取第一个[0],表示取了":{"cid":"377149574"}这个对象,然后再用GetValue("cid")把对象的值取出来。
*/
namespace web
{
/// <summary>
/// JSON解析器
/// </summary>
public class CommonJsonModel:clsJson
{
//原文参考: http://www.cnblogs.com/loalongblogs/archive/2011/09/03/2165406.html
private string rawjson;
private bool isValue = false;
private bool isModel = false;
private bool isCollection = false;
internal CommonJsonModel(string rawjson)
{
this.rawjson = rawjson;
if (string.IsNullOrEmpty(rawjson))
throw new Exception("missing rawjson");
rawjson = rawjson.Trim();
if (rawjson.StartsWith("{"))
{
isModel = true;
}
else if (rawjson.StartsWith("["))
{
isCollection = true;
}
else
{
isValue = true;
}
}
public string Rawjson
{
get { return rawjson; }
}
public bool IsValue()
{
return isValue;
}
public bool IsValue(string key)
{
if (!isModel)
return false;
if (string.IsNullOrEmpty(key))
return false;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
return submodel.IsValue();
}
}
return false;
}
public bool IsModel()
{
return isModel;
}
public bool IsModel(string key)
{
if (!isModel)
return false;
if (string.IsNullOrEmpty(key))
return false;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
return submodel.IsModel();
}
}
return false;
}
public bool IsCollection()
{
return isCollection;
}
public bool IsCollection(string key)
{
if (!isModel)
return false;
if (string.IsNullOrEmpty(key))
return false;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
return submodel.IsCollection();
}
}
return false;
}
/// <summary>
/// 当模型是对象,返回拥有的key
/// </summary>
/// <returns></returns>
public List<string> GetKeys()
{
if (!isModel)
return null;
List<string> list = new List<string>();
foreach (string subjson in base._GetCollection(this.rawjson))
{
string key = new CommonJsonModel(subjson).Key;
if (!string.IsNullOrEmpty(key))
list.Add(key);
}
return list;
}
/// <summary>
/// 当模型是对象,key对应是值,则返回key对应的值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetValue(string key)
{
if (!isModel)
return null;
if (string.IsNullOrEmpty(key))
return null;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
return model.Value;
}
return null;
}
/// <summary>
/// 模型是对象,key对应是对象,返回key对应的对象
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public CommonJsonModel GetModel(string key)
{
if (!isModel)
return null;
if (string.IsNullOrEmpty(key))
return null;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
if (!submodel.IsModel())
return null;
else
return submodel;
}
}
return null;
}
/// <summary>
/// 模型是对象,key对应是集合,返回集合
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public CommonJsonModel GetCollection(string key)
{
if (!isModel)
return null;
if (string.IsNullOrEmpty(key))
return null;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
if (!submodel.IsCollection())
return null;
else
return submodel;
}
}
return null;
}
/// <summary>
/// 模型是集合,返回自身
/// </summary>
/// <returns></returns>
public List<CommonJsonModel> GetCollection()
{
List<CommonJsonModel> list = new List<CommonJsonModel>();
if (IsValue())
return list;
foreach (string subjson in base._GetCollection(rawjson))
{
list.Add(new CommonJsonModel(subjson));
}
return list;
}
/// <summary>
/// 当模型是值对象,返回key
/// </summary>
private string Key
{
get
{
if (IsValue())
return base._GetKey(rawjson);
return null;
}
}
/// <summary>
/// 当模型是值对象,返回value
/// </summary>
private string Value
{
get
{
if (!IsValue())
return null;
return base._GetValue(rawjson);
}
}
}
}
第二步:在Flash中调用w.txt,将变量值传递给动态文本框,文本框实例名分别为txtWeather,txtTemp,txtWind。
在Flash的第一帧中加入代码:

System.useCodepage = true;//让中文能被识别,不出现乱码
var htmlload= new LoadVars();
htmlload.load("../Weather.aspx")//执行aspx,以更新txt文件内容
var Txtload= new LoadVars();
Txtload.onLoad = function(success) {
if (success) {
trace("载入成功!");
trace(Txtload.weather)
trace(Txtload.temp)
trace(Txtload.wind)
txtWeather.text = Txtload.weather;
txtTemp.text = Txtload.temp;
txtWind.text = Txtload.wind;
} else {
trace("载入失败!");
//gotoAndStop("shibai")
}
};
Txtload.load("../w.txt")
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)