2013-0730

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

作者: momy 分类: 编程开发 3 Comment »
摘要:C#使用百度API通过IP获取地理位置和坐标

百度接口相关说明: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;
}

返回的是相关类对象,直接取属性即可获得相关内容。

标签: C# 百度API 通过IP获取位置 IP获取坐标 阅读: 11693
上一篇: 常用正则表达式 - 3455次
下一篇: MVC上传文件时HttpPostedFileBase file为null的问题 - 18326次

网友评论

42.81.46.* 2015/12/28 17:28:44

key是多少呀

103.44.205.* 2016/8/11 22:27:06

key 自己申请啊

180.118.105.* 2016/10/17 21:33:21

什么都搞了 就是不行啊   Key也申请了 是for  server的 你们做出来没啊 

向右滑动解锁留言