利用淘宝IP查询接口,免费查询IP归属地

这个接口比其他网站提供的接口都好,查询限制是每个用户的访问频率需小于10qps,也就是说每秒限制10次查询,几乎可以说是无限制了

接口使用说明:

1. 请求接口(GET):

http://ip.taobao.com/service/getIpInfo.php?ip=[ip地址字串]

2. 响应信息:

(json格式的)国家 、省(自治区或直辖市)、市(县)、运营商

3. 返回数据格式:

1
2
3
4
{ "code" :0, "data" :{ "ip" : "210.75.225.254" , "country" : "\u4e2d\u56fd" , "area" : "\u534e\u5317" ,
"region" : "\u5317\u4eac\u5e02" , "city" : "\u5317\u4eac\u5e02" , "county" : "" , "isp" : "\u7535\u4fe1" ,
"country_id" : "86" , "area_id" : "100000" , "region_id" : "110000" , "city_id" : "110000" ,
"county_id" : "-1" , "isp_id" : "100017" }}

其中code的值的含义为,0:成功,1:失败。

按照说明要求,我们需要封装以下几个方法:

1、请求接口

1
2
3
4
5
6
7
8
9
10
11
/// <summary>
/// 请求淘宝API,获取返回的Json结果
/// </summary>
/// <param name="ipAddress">IP地址</param>
/// <returns></returns>
string  GetAPI( string  ipAddress)
{
     var web =  new  WebClient();
     var result = web.DownloadString( "http://ip.taobao.com/service/getIpInfo.php?ip="  + ipAddress);           
     return  UnicodeToChinese(result);
}

2 、unicode编码转换函数(我们看到,淘宝API返回的json中,把中文做了unicode编码处理,所以我们要将其结果转换为中文)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/// <summary>
/// 将Unicode转换为中文
/// </summary>
/// <param name="str">Unicode原文</param>
/// <returns></returns>
string  UnicodeToChinese( string  str)
{
     string  outStr =  "" ;
     Regex reg =  new  Regex( @"(?i)\\u([0-9a-f]{4})" );
     outStr = reg.Replace(str, m1=>
     {
         return  (( char )Convert.ToInt32(m1.Groups[1].Value, 16)).ToString();
     });
     return  outStr;
}

3、获取指定的Json数据(因为API返回的Json数据比较简单,我们不用专门去写一个Json解析类,或调用第三方Json处理组件,用正则就能搞定)

1
2
3
4
5
6
7
8
9
10
11
/// <summary>
/// 获取指定Json数据
/// </summary>
/// <param name="key">指定的Json字段,我们用key来表示</param>
/// <param name="jsonText">Json原文</param>
/// <returns></returns>
string  GetJsonValue( string  key,  string  jsonText)
{
     Regex reg =  new  Regex( string .Format( "\"{0}\":{1}," , key,  "(.*?)" ));
     return  reg.Match(jsonText).Groups[1].ToString().Replace( "\"" "" );
}

下面介绍下使用方法代码:

1
2
3
4
5
6
7
8
9
10
11
12
var  jsonText = GetAPI( this .txt_Ip.Text);  //查询输入框内的IP
var  code = GetJsonValue( "code" , jsonText);  //其中code的值的含义为,0:成功,1:失败
var  country = GetJsonValue( "country" , jsonText);  //国家
var  region = GetJsonValue( "region" , jsonText);  //省份
var  city = GetJsonValue( "city" , jsonText);  //城市
var  county = GetJsonValue( "county" , jsonText);  //县
var  isp = GetJsonValue( "isp" , jsonText);  //运营商
var  allText =  new  string[] {country, region, city, county, isp};  //合并结果为数组
if  (code ==  "0" //表示成功
     this .lb_Result.Text = string.Join( "-" , allText);  //用-间隔分开输出结果
else
     this .lb_Result.Text =  "IP归属地查询失败!" ;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值