您的位置:首页 > 编程语言 > C#

c# 天气预报

2016-01-25 16:19 459 查看
转载请注明出处:http://blog.csdn.net/u013668852/article/details/50581065
一、天气查询接口
百度天气预报api是一款免费的天气预报接口

接口示例:

http://api.map.baidu.com/telematics/v3/weather?output=json&ak=xxxxxxxxxxKt8&location=你想要查询的地方,如徐州。

其中的ak是许要自己到百度进行申请的,这里给贴出一个其他人申请的,亲测可用,建议还是自己申请一个: 6tYzTvGZSOpYB5Oc2YGGOKt8

申请地址:http://lbsyun.baidu.com/apiconsole/key

其中的output参数是可选的,可以是xml或者是json,若选择json,返回的天气数据就是json格式的,那么数据的解析就是json格式的解析,如果你喜欢xml,也是一个很好的选择,json格式的数据往往传递较大数据的时候较为快捷,因为不像xml存在那么多的标签,减少数据传递量。

二、发起Http请求
Ok,既然接口的事情解决,接下来就是进行http请求的模拟了,这里选择get方式的请求,具体代码如下:

//这里只是WeatherHelper的部分代码

public class WeatherHelper
{
public const Stringservice_http = "http://api.map.baidu.com/telematics/v3/weather?output=json&ak=6tYzTvGZSOpYB5Oc2YGGOKt8&location=";//这里使用了别人的百度ak(密钥),有需要的话自己申请
public String location = "";
public String http="";
public WeatherHelper(Stringlocation)
{
this.location =location;
http = service_http +location;
}
public string HttpGet()
{
HttpWebRequest request= (HttpWebRequest)WebRequest.Create(http);
request.Method = "GET";
// request.ContentType= "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreammyResponse Stream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString =myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
}

httpGet()返回的是json格式的字符串,接下来就是进行json解析

三、Json的序列化与反序列化
可以参考下:http://www.tuicool.com/articles/AniEZ3
但是我不推荐使用这篇文章中的json解析方法,因为他们对多重json的解析不是很好,我选择了Newtonsoft.Json提供的json解析方法,下面的代码是返回的json格式示例。

<pre name="code" class="csharp">{
"error": 0,
"status": "success",
"date": "2016-01-25",
"results": [
{
"currentCity": "徐州",
"pm25": "78",
"index": [
{
"title": "穿衣",
"zs": "冷",
"tipt": "穿衣指数",
"des": "天气冷,建议着棉服、羽绒服、皮夹克加羊毛衫等冬季服装。年老体弱者宜着厚棉衣、冬大衣或厚羽绒服。"
},
{
"title": "洗车",
"zs": "较适宜",
"tipt": "洗车指数",
"des": "较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。"
},
{
"title": "旅游",
"zs": "一般",
"tipt": "旅游指数",
"des": "天气较好,温度稍低,而且风稍大,让您感觉有些冷,会对外出有一定影响,外出注意防风保暖。"
},
{
"title": "感冒",
"zs": "易发",
"tipt": "感冒指数",
"des": "昼夜温差很大,易发生感冒,请注意适当增减衣服,加强自我防护避免感冒。"
},
{
"title": "运动",
"zs": "较不宜",
"tipt": "运动指数",
"des": "天气较好,但考虑天气寒冷,风力较强,推荐您进行室内运动,若户外运动请注意保暖并做好准备活动。"
},
{
"title": "紫外线强度",
"zs": "弱",
"tipt": "紫外线强度指数",
"des": "紫外线强度较弱,建议出门前涂擦SPF在12-15之间、PA+的防晒护肤品。"
}
],
"weather_data": [
{
"date": "周一 01月25日 (实时:2℃)",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/qing.png",
"weather": "晴",
"wind": "西风3-4级",
"temperature": "1 ~ -8℃"
},
{
"date": "周二",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/qing.png",
"weather": "晴",
"wind": "西风微风",
"temperature": "5 ~ -5℃"
},
{
"date": "周三",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/yin.png",
"weather": "晴转阴",
"wind": "东风微风",
"temperature": "7 ~ -3℃"
},
{
"date": "周四",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/xiaoyu.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/zhongyu.png",
"weather": "小雨转小到中雨",
"wind": "东风3-4级",
"temperature": "7 ~ 1℃"
}
]
}
]
}



我们需要做些前提准备,就是持久化对象的建立:

public class WeatherMessage
{
[DataMember]
public String error { get;set; }
[DataMember]
public String status { get;set; }
[DataMember]
public String date { get; set;}
[DataMember]
public WeatherModel[]results{ get; set; }

}
public class WeatherModel
{
[DataMember]
public String currentCity{ get; set; }
[DataMember]
public String pm25 { get; set;}
[DataMember]
public Weather_data[]weather_data { get; set; }
}
public class Weather_data
{
public String date { get; set;}
public StringdayPictureUrl { get; set; }
public StringnightPictureUrl { get; set; }
public String weather { get;set; }
public String wind { get; set;}
public String temperature{ get; set; }
}


准备工作完成,下面就是json数据向对象的映射:

public WeatherMessage GetWeather()
{

WeatherMessage weatherMessage =JsonConvert.DeserializeObject<WeatherMessage>(HttpGet());
return weatherMessage;
}
四、数据的显示

你可以把获得的数据在web中或者在app中显示,我简单的用web显示为例

 


protected void Button1_Click(object sender, EventArgs e)
{
if(TextBox2.Text.ToString().Trim() == null)
{
TextBox2.Focus();
}
else
{
String location =TextBox2.Text.Trim();
WeatherHelperhelper = new WeatherHelper(location);
WeatherMessageweathermessage = helper.GetWeather();
String content = "";
if(weathermessage.status.Equals("success"))
{
WeatherModel weatherModel= weathermessage.results[0];
content =content + weatherModel.currentCity + "\n";
Weather_data[]weather_datas = weatherModel.weather_data;
for (int i =0; i <=weather_datas.Length - 1; i++)
{
content =content + weather_datas[i].date + "\n";
content =content + weather_datas[i].weather + "\n";
content =content + weather_datas[i].temperature + "\n";
content =content + weather_datas[i].wind + "\n";
}
TextBox1.Text= content;
}
else
{
TextBox1.Text= "对不起,没有查询到你要查询的城市";
}
}
}

}


源码下载地址
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c#天气预报