最近公司让做一个用户登录、付费的时候记录操作人的地理位置。
搜了很多帖子,一开始用的淘宝的api,但是用了一段时间发现,这个api当获取的次数多了之后,就报404了,导致很多记录没有记录地址,虽然淘宝这个api的位置很全精确到市县级,但是404的次数太多,并不实用。
淘宝API
缺点:
1.有时候调用速度很快,但是有时候回超过30秒而导致服务器报错,终结页面的运行
<?php
$ip = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$_GET["ip"]);
$ip = json_decode($ip,true);
?>
结果是返回JSON格式的如下
腾讯API
缺点:好像用户试用WIFI情况下定位不准确或者不会有返回数据
http://ip.taobao.com/service/getIpInfo.php?ip=IP
结果是返回JSON格式(别人告诉的,我测试并不好使)
搜狐API
缺点:
1.不能使用特定IP来查询,只能使用API原本查询的IP
2.在服务器测试中,API直接查询出了服务器的IP,并不是用户的IP
(这两个缺点感觉是我写代码的问题,但是我不知道怎么解,如果有大神解决了麻烦告诉我一下怎么解,谢谢)
搜狐IP地址查询接口(默认GBK):http://pv.sohu.com/cityjson
搜狐IP地址查询接口(可设置编码):http://pv.sohu.com/cityjson?ie=utf-8
搜狐另外的IP地址查询接口:http://txt.go.sohu.com/ip/soip
第一个和第二个分别是不同编码的API,返回结果如下
第三个API虽然有结果原谅我小白看不懂怎么使用,返回结果如下
126API
缺点:返回格式有点问题,不是UTF-8格式,转格式也失败
126API:http://ip.ws.126.net/ipquery?ip=IP
返回结果如下
由此可见以上API虽然都能搜寻出来所在地理位置,但是不精确,而且格式很乱,不易于使用,最后给大家推荐一款功能强大而且实用的api,那就是
太平洋API
这个API很强大:http://whois.pconline.com.cn
详细的看一下里面的说明吧!
我采用的是
http://whois.pconline.com.cn/ipJson.jsp?callback=testJson&ip=IP
这个链接;
这是返参:定位很明确。
给大家付上代码:
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("gbk")));
String jsonText = readAll(rd);
jsonText = jsonText.replace("if(window.testJson)","");
jsonText = jsonText.substring(21);
jsonText = jsonText.substring(0,jsonText.length()-10);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
// System.out.println("同时 从这里也能看出 即便return了,仍然会执行finally的!");
}
}
public static void main(String[] args) {
JSONObject json = readJsonFromUrl(
"http://whois.pconline.com.cn/ipJson.jsp?callback=testJson&ip="+ip);
System.out.println(json.toString());
System.out.println(json.get("addr"));
}
最后直接获取addr这个值就可以了.