根据ip获取用户地理位置

时间:2023-03-09 08:12:05
根据ip获取用户地理位置

各大网站都提供根据ip获取用户地理位置信息,这里以新浪的接口为例子

接口地址为:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=218.18.171.146

代码:

         #region 根据ip获取地点
/// 获取Ip归属地
/// </summary>
/// <param name="ip">ip</param>
/// <returns>归属地</returns>
public static string GetIpAddress(string ip)
{
JavaScriptSerializer Jss = new JavaScriptSerializer();
//http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=218.18.171.146 调用新浪的接口
//var remote_ip_info = {"ret":1,"start":-1,"end":-1,"country":"\u4e2d\u56fd","province":"\u5e7f\u4e1c","city":"\u6df1\u5733","district":"","isp":"","type":"","desc":""};
string address = string.Empty;
try
{
string reText = WebRequestPostOrGet("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip="+ip, "");
reText = reText.Split('=')[].Split(';')[].Trim();
Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(reText);
address = DicText["city"].ToString();
}
catch { }
return address;
}
#endregion

其中WebRequestPostOrGet方法:

         #region Post/Get提交调用抓取
/// <summary>
/// Post/get 提交调用抓取
/// </summary>
/// <param name="url">提交地址</param>
/// <param name="param">参数</param>
/// <returns>string</returns>
public static string WebRequestPostOrGet(string sUrl, string sParam)
{
byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam); Uri uriurl = new Uri(sUrl);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);//HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + (url.IndexOf("?") > -1 ? "" : "?") + param);
req.Method = "Post";
req.Timeout = * ;
req.ContentType = "application/x-www-form-urlencoded;";
req.ContentLength = bt.Length; using (Stream reqStream = req.GetRequestStream())//using 使用可以释放using段内的内存
{
reqStream.Write(bt, , bt.Length);
reqStream.Flush();
}
try
{
using (WebResponse res = req.GetResponse())
{
//在这里对接收到的页面内容进行处理 Stream resStream = res.GetResponseStream(); StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8); string resLine; System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder(); while ((resLine = resStreamReader.ReadLine()) != null)
{
resStringBuilder.Append(resLine + System.Environment.NewLine);
} resStream.Close();
resStreamReader.Close(); return resStringBuilder.ToString();
}
}
catch (Exception ex)
{
return ex.Message;//url错误时候回报错
}
}
#endregion Post/Get提交调用抓取