本文整理自网络,侵删。
网上搜了一下资料,发现公开的查询 API 有几个:
1. 新浪的。访问了,没有结果返回;
2. 腾讯的。访问了,返回结果是这个页面已经找不到。
3. 淘宝的,能用。
淘宝的 API 接口:http://ip.taobao.com/service/getIpInfo.php?ip=
这是一个 http 的调用,返回值是 JSON 格式。可以直接用浏览器去访问这个 URL 然后看到返回值。
例子:
http://ip.taobao.com/service/getIpInfo.php?ip=103.45.2.23
返回值是:
{"code":0,"data":{"ip":"103.45.2.23","country":"中国","area":"","region":"广东","city":"东莞","county":"XX","isp":"电信","country_id":"CN","area_id":"","region_id":"440000","city_id":"441900","county_id":"xx","isp_id":"100017"}}
上述 JSON 的格式,用 DELPHI 的代码是可以解析的。
从一个 HTTP 的 URL 获取返回值,最简单的办法是用 Indy 的 TIdHTTP 控件。
例子代码如下:procedure TFmMain.BtnIPQueryClick(Sender: TObject);var S: string; JSONStr: string; country, area, region, city: string;begin //EditIP 是输入的要查询的 IP 地址 S := 'http://ip.taobao.com/service/getIpInfo.php?ip=';
JSONStr := IdHTTP1.Get(S + EditIP.Text); if JSONStr = '' then Exit;
ParseIPAddressFromTaoBaoJSON(JSONStr, country, area, region, city); Memo1.Lines.Add(country + '; ' + area + '; ' + region + '; ' + City);end;
上述代码中使用了一个专门针对淘宝返回的 JSON 的字符串解析的函数ParseIPAddressFromTaoBaoJSON
这个函数使用了 TJSONValue 需要 uses System.JSON;
代码如下:function TFmMain.ParseIPAddressFromTaoBaoJSON(const JSONStr: string; var country, area, region, city: string): Boolean;var Obj: TJSONValue; AValue: TJSONValue;begin Obj := TJSONObject.ParseJSONValue(JSONStr);
if Obj is TJSONObject then begin AValue := TJSONObject(Obj).Values['data']; end;
if AValue is TJSONObject then begin country := TJSONObject(AValue).Values['country'].ToString; area := TJSONObject(AValue).Values['area'].ToString; region := TJSONObject(AValue).Values['region'].ToString; city := TJSONObject(AValue).Values['city'].ToString; end;end;这段代码,目前测试通过。日期:2018-6-24. 未来是否能用,得看淘宝的这个服务是否还在。
相关阅读 >>
winapi 字符及字符串函数(8): ischarupper - 是否是个大写字母
Delphi getprocessisadmin()判断exe是否以管理员身份启动
Delphi changefileext 更改文件的后缀扩展名
更多相关阅读请进入《Delphi》频道 >>