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

百度接口相关说明:http://developer.baidu.com/map/ip-location-api.htm

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

 1 #region AddressForQueryIPFromBaidu
 2 [Serializable]
 3 public class AddressForQueryIPFromBaidu
 4 {
 5     public string Address { get; set; }
 6     public Content Content { get; set; }
 7     public string Status { get; set; }
 8 }
 9 [Serializable]
10 public class Content
11 {
12     public string Address { get; set; }
13     public Address_Detail Address_Detail { get; set; }
14     public Point Point { get; set; }
15 }
16 [Serializable]
17 public class Address_Detail
18 {
19     public string City { get; set; }
20     public string City_Code { get; set; }
21     public string District { get; set; }
22     public string Province { get; set; }
23     public string Street { get; set; }
24     public string Street_Number { get; set; }
25 }
26 [Serializable]
27 public class Point
28 {
29     public string X { get; set; }
30     public string Y { get; set; }
31 }
32 #endregion

接口调用方法:

 1 public static AddressForQueryIPFromBaidu GetAddressFromIP(string ipAddress)
 2 {
 3     string baiduKey = "59722ea6a425fbd81******80ee3ecbb";
 4     string url = "http://api.map.baidu.com/location/ip?ak="+baiduKey+"&ip="+ipAddress+"&coor=bd09ll";
 5     HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
 6     HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 7     System.IO.Stream responseStream = response.GetResponseStream();
 8     System.IO.StreamReader sr = new System.IO.StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
 9     string responseText = sr.ReadToEnd();
10     sr.Close();
11     sr.Dispose();
12     responseStream.Close();
13     string jsonData = responseText;
14     JavaScriptSerializer jss = new JavaScriptSerializer();
15     AddressForQueryIPFromBaidu addressForQueryIPFromBaidu = jss.Deserialize<AddressForQueryIPFromBaidu>(jsonData);
16     return addressForQueryIPFromBaidu;
17 }

 

转载于:https://www.cnblogs.com/CrazyAnts/p/3680631.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值