/// <summary>
/// 获取天气预报信息
/// </summary>
/// <returns></returns>
public BaiduTQ GetWeather()
{
// GetCity()获得的信息解析后,填充丰台部分
string url = @"http://api.map.baidu.com/telematics/v3/weather?location=丰台&output=json&ak=hXWAgbsCC9UTkBO5V5Qg1WZ9"; HttpWebRequest webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
webRequest.Method = "GET";
webRequest.ContentType = "text/html"; using(StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
string str = sr.ReadToEnd();
BaiduTQ b = JsonConvert.DeserializeObject<BaiduTQ>(str); return b;
}
}
获取天气预报信息
public class BaiduTQ
{
public int error { get; set; }
public string status { get; set; }
public string date { get; set; }
public List<BaiduResult> results { get; set; }
} public class BaiduResult
{
public string currentCity { get; set; }
public string pm25 { get; set; }
public List<BaiduIndex> index { get; set; }
public List<BaiDuWeaterData> weather_data { get; set; }
} public class BaiduIndex
{
public string title { get; set; }
public string zs { get; set; }
public string tipt { get; set; }
public string des { get; set; }
} public class BaiDuWeaterData
{
public string date { get; set; }
public string dayPictureUrl { get; set; }
public string nightPictureUrl { get; set; }
public string weather { get; set; }
public string wind { get; set; }
public string temperature { get; set; }
}
BaiduTQ
/// <summary>
/// 根据ip获取城市信息
/// </summary>
/// <returns>ip所在城市信息</returns>
private string GetCity()
{
IPAddress ip = this.GetIPAddress();
if (ip == null) return null; using (var client = new WebClient())
{
var url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
client.Encoding = Encoding.UTF8;
var str = client.DownloadString(url); return str;
}
}
根据ip获取所在地
/// <summary>
/// 获取本地ip地址
/// </summary>
/// <returns></returns>
private IPAddress GetIPAddress()
{
IPAddress[] arrIPAddresses = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in arrIPAddresses)
{
if (ip.AddressFamily.Equals(AddressFamily.InterNetwork))
{
return ip;
}
} return null;
}
获取本地ip
ps:若需要获取外网ip,请参见http://www.cnblogs.com/hehexiaoxia/p/4996624.html