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

C#使用百度API通过IP获取地理位置和坐标

2014-04-22 15:28 1001 查看
百度接口相关说明:http://developer.baidu.com/map/ip-location-api.htm

返回是json格式,首先构建相关反系列化类:

#region AddressForQueryIPFromBaidu
[Serializable]
public class AddressForQueryIPFromBaidu
{
public string Address { get; set; }
public Content Content { get; set; }
public string Status { get; set; }
}
[Serializable]
public class Content
{
public string Address { get; set; }
public Address_Detail Address_Detail { get; set; }
public Point Point { get; set; }
}
[Serializable]
public class Address_Detail
{
public string City { get; set; }
public string City_Code { get; set; }
public string District { get; set; }
public string Province { get; set; }
public string Street { get; set; }
public string Street_Number { get; set; }
}
[Serializable]
public class Point
{
public string X { get; set; }
public string Y { get; set; }
}
#endregion


接口调用方法:

public static AddressForQueryIPFromBaidu GetAddressFromIP(string ipAddress)
{
string baiduKey = "59722ea6a425fbd81******80ee3ecbb";
string url = "http://api.map.baidu.com/location/ip?ak="+baiduKey+"&ip="+ipAddress+"&coor=bd09ll";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
string responseText = sr.ReadToEnd();
sr.Close();
sr.Dispose();
responseStream.Close();
string jsonData = responseText;
JavaScriptSerializer jss = new JavaScriptSerializer();
AddressForQueryIPFromBaidu addressForQueryIPFromBaidu = jss.Deserialize<AddressForQueryIPFromBaidu>(jsonData);
return addressForQueryIPFromBaidu;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: