最近的一个项目中需要记录用户登录的物理地址,但是目前我们已知的只是IP地址,所以就需要根据IP查询所对应的物理信息。
自建IP库我想肯定是不现实的,因为数据量太大。百度了下发现有很多提供api接口的,比如百度、新浪、淘宝等等,经过一番折腾感觉还是淘宝的api最好用,不用注册、没有限制、调用简单、有官方帮助。下面我分享下我所编写的一个帮助类。
注意事项:
- 注意添加相关引用
- 添加第三方类库:using Newtonsoft.Json;
助手类完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
using Newtonsoft.Json; using System; using System.IO; using System.Net; using System.Text; namespace WeatherDemo { /// <summary> /// /// 功能:调用淘宝IP库获取指定ip的相关详细,其中包括国家、省份、城市、运营商等 /// 作者:邹学典 /// 时间:2015-11-12 /// 版本:V1.0 /// 备注: /// 1、接口调用地址:http://ip.taobao.com/service/getIpInfo.php /// 2、官方帮助地址:http://ip.taobao.com/index.php /// 3、代码出自:https://ityouzi.com/archives/taobao-get-ip-info-api.html /// /// </summary> public class GetIpInfoAPI { /// <summary> /// 根据IP地址获取ip相关信息 /// </summary> /// <param name="ip">ip地址</param> /// <returns>获取数据失败返回null</returns> public static IpInfo GetInfoByIp(string ip) { try { string url = "http://ip.taobao.com/service/getIpInfo.php?ip="+ip; var resultJson = GetIpInfoAPI.HttpGet(url); string value = JsonConvert.DeserializeObject(resultJson).ToString(); IpInfo model = JsonConvert.DeserializeObject<IpInfo>(value); return model; } catch (Exception) { } return null; } /// <summary> /// 后台发送GET请求 /// </summary> /// <param name="url">服务器地址</param> /// <returns></returns> public static string HttpGet(string url) { try { //创建Get请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; //接受返回来的数据 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8")); string retString = streamReader.ReadToEnd(); streamReader.Close(); stream.Close(); response.Close(); return retString; } catch ( Exception) { return ""; } } } #region 其他ip相关类 public class IpInfo { public int code { get; set; } public Data data { get; set; } } public class Data { 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; } } #endregion } |
1 |
<br> |
使用方法
1 |
string ip = "114.80.174.102";//为测试所以写假数据<br> IpInfo ipInfo = GetIpInfoAPI.GetInfoByIp(ip);<br> |
调用结果:
发布者:柚子,转转请注明出处:https://ityouzi.com/archives/taobao-get-ip-info-api.html