在上一篇中我们获取到了Ip地址,下一步我们就可以根据Ip地址获取所在地区.
在这里,我使用第三方定位服务:淘宝的Ip地址库
只需要调用淘宝的Ip地址库就能查询到所在地区.
淘宝Ip地址库链接:
http://ip.aliyun.com/instructions.html
在上图中可以看见,我们需要调用的API地址和所需参数以及返回的数据格式
请求接口地址:'' http://ip.taobao.com/service/getIpInfo.php?ip=xxxx',我们只需要提供IP地址即可
在返回的数据格式中,我们需要将其Json数据转为实体类.
后台代码:
第一步: 通过c#远程请求数据
方法封装:WebRequestHeler工具类
public static class WebRequestHelper
{
/// <summary>
///以Get方式根据提供的地址 获取数据
/// </summary>
/// <param name="url">以Get方式根据提供的地址</param>
/// <returns></returns>
public static string GetUrl(string url)
{
string resultstring = string.Empty;
Encoding encoding = Encoding.UTF8;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//这里的url指要获取的数据网址
request.Method = "GET";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
resultstring = reader.ReadToEnd();
}
}
catch (Exception)
{
throw;
}
return resultstring;
}
}
.
第二步:建立实体类.
public class IpAddressInfo
{
public int code { get; set; }
public DataList data { get; set; }
}
public class DataList
{
public string ip { get; set; }
public string country { get; set; }
public string area { get; set; }
public string region { get; set; }
public string city { get; set; }
public string county { get; set; }
public string isp { get; set; }
public string country_id { get; set; }
public string area_id { get; set; }
public string region_id { get; set; }
public string city_id { get; set; }
public string county_id { get; set; }
public string isp_id { get; set; }
}
第三步:封装Json反序列化工具类方法
public static class JsonHelper
{
/// <summary>
/// 反序列化 将Json数据转为实体类
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonStr"></param>
/// <returns></returns>
public static T StringToEnteity<T>(string jsonStr) where T : class
{
try
{
return JsonConvert.DeserializeObject<T>(jsonStr);
}
catch (Exception ex)
{
string error = ex.Message;
return null;
}
}
}
第四步:根据Ip获取真实的地址.
//假定IP地址是:120.79.252.67
string IpAddress = "120.79.252.67";//模拟获取访问者的Ip地址
//拼接查询路径
string url="http://ip.taobao.com/service/getIpInfo.php?ip="+IpAddress +"";
//调用远程访问Get方法
string strJson=WebRequestHelper.GetUrl(url);//返回Json数据
//反序列化 取得返回结果
IpAddressInfo inf = JsonHelper.StringToEnteity<IpAddressInfo>(strJson);
//然后即可获取所需要的信息
//比如:
//国家:inf.data.country;
//省:inf.data.region;
//市:inf.data.city;
//通讯网络;inf.data.isp
原文地址: