这个接口比其他网站提供的接口都好,查询限制是每个用户的访问频率需小于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();
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归属地查询失败!"
;
|