各大网站都提供根据ip获取用户地理位置信息,这里以新浪的接口为例子
接口地址为:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=218.18.171.146
代码:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #region 根据ip获取地点 2 /// 获取Ip归属地 3 /// </summary> 4 /// <param name="ip">ip</param> 5 /// <returns>归属地</returns> 6 public static string GetIpAddress(string ip) 7 { 8 JavaScriptSerializer Jss = new JavaScriptSerializer(); 9 //http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=218.18.171.146 调用新浪的接口 10 //var remote_ip_info = {"ret":1,"start":-1,"end":-1,"country":"\u4e2d\u56fd","province":"\u5e7f\u4e1c","city":"\u6df1\u5733","district":"","isp":"","type":"","desc":""}; 11 string address = string.Empty; 12 try 13 { 14 string reText = WebRequestPostOrGet("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip="+ip, ""); 15 reText = reText.Split('=')[1].Split(';')[0].Trim(); 16 Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(reText); 17 address = DicText["city"].ToString(); 18 } 19 catch { } 20 return address; 21 } 22 #endregion
其中WebRequestPostOrGet方法:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #region Post/Get提交调用抓取 2 /// <summary> 3 /// Post/get 提交调用抓取 4 /// </summary> 5 /// <param name="url">提交地址</param> 6 /// <param name="param">参数</param> 7 /// <returns>string</returns> 8 public static string WebRequestPostOrGet(string sUrl, string sParam) 9 { 10 byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam); 11 12 Uri uriurl = new Uri(sUrl); 13 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);//HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + (url.IndexOf("?") > -1 ? "" : "?") + param); 14 req.Method = "Post"; 15 req.Timeout = 120 * 1000; 16 req.ContentType = "application/x-www-form-urlencoded;"; 17 req.ContentLength = bt.Length; 18 19 using (Stream reqStream = req.GetRequestStream())//using 使用可以释放using段内的内存 20 { 21 reqStream.Write(bt, 0, bt.Length); 22 reqStream.Flush(); 23 } 24 try 25 { 26 using (WebResponse res = req.GetResponse()) 27 { 28 //在这里对接收到的页面内容进行处理 29 30 Stream resStream = res.GetResponseStream(); 31 32 StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8); 33 34 string resLine; 35 36 System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder(); 37 38 while ((resLine = resStreamReader.ReadLine()) != null) 39 { 40 resStringBuilder.Append(resLine + System.Environment.NewLine); 41 } 42 43 resStream.Close(); 44 resStreamReader.Close(); 45 46 return resStringBuilder.ToString(); 47 } 48 } 49 catch (Exception ex) 50 { 51 return ex.Message;//url错误时候回报错 52 } 53 } 54 #endregion Post/Get提交调用抓取