在考虑获取天气代码上,采用了《中国天气网的信息》网上很多方法都是直接使用网页嵌套的方式来实现,对于Web App 这是非常正确的,要不然获取的就是服务器所在地的天气状况,本例主要用在WinForm上面;
代码可以自动获取当前IP所在的城市,然后通过城市ID来获取当前城市的天气情况;
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace BlogPromotion
{
///
/// 获取当地的天气状况
///
public class WeatherGet
{
///
/// 获取城市代码
///
///
private static string GetCityId()
{
HttpWebRequest wNetr = (HttpWebRequest)HttpWebRequest.Create("http://61.4.185.48:81/g/");
HttpWebResponse wNetp = (HttpWebResponse)wNetr.GetResponse();
wNetr.ContentType = "text/html";
wNetr.Method = "Get";
Stream Streams = wNetp.GetResponseStream();
StreamReader Reads = new StreamReader(Streams, Encoding.UTF8);
String ReCode = Reads.ReadToEnd();
//关闭暂时不适用的资源
Reads.Dispose();
Streams.Dispose();
wNetp.Close();
//分析返回代码
String[] Temp = ReCode.Split(';');
ReCode = Temp[1].Replace("var id=", "");
return ReCode;
}
///
/// 获取城市的天气状况
///
///
public static string GetWeather()
{
string wUrl = string.Format("http://m.weather.com.cn/data/{0}.html",GetCityId());
HttpWebRequest wNetr = (HttpWebRequest)HttpWebRequest.Create(wUrl);
HttpWebResponse wNetp = (HttpWebResponse)wNetr.GetResponse();
wNetr.ContentType = "text/html";
wNetr.Method = "Get";
Stream Streams = wNetp.GetResponseStream();
StreamReader Reads = new StreamReader(Streams, Encoding.UTF8);
String ReCode = Reads.ReadToEnd();
//关闭暂时不适用的资源
Reads.Dispose();
Streams.Dispose();
wNetp.Close();
//分析返回代码
String[] Splits = new String[] { "\"",",","\"" };
String[] Temp = ReCode.Split(Splits,StringSplitOptions.RemoveEmptyEntries);
ReCode = String.Format("天气:{0} {1} {2}",Temp[5],Temp[62],Temp[26]);
return ReCode;
}
}
}