由于刚好我的web有这两个jar,所以就直接用到了commons-net.jar和org.json.jar
public static void main(String[] args) {
String ip = "110.83.46.180";
String Zone = GetZone("http://apis.juhe.cn/ip/ip2addr?ip="+ip+"&dtype=&key=54d7b1689c44658a9b83a09250024450");
System.out.println("结果IP:"+Zone);
}
private static String GetZone(String ipUrl){
//返回结果
String result = "获取失败!";
//每行
String line = "";
//读取JSON结果
String json = "";
try {
URL url = new URL(ipUrl);
HttpURLConnection httpUrl = (HttpURLConnection)url.openConnection();
httpUrl.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
httpUrl.setDoOutput(true);
BufferedReader in = new BufferedReader(new InputStreamReader(httpUrl.getInputStream(),"UTF-8"));
while((line=in.readLine())!=null){
json+=line;
}
in.close();
JSONObject obj = new JSONObject(json);
result = obj.getJSONObject("result").getString("area")+"-"+obj.getJSONObject("result").getString("location");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
返回结果例图
用了一上午,发现上面哪个接口TM尽然有限制;然后换下面接口
public static String getZone(String ip){
String result = "获取失败!";
try {
URL url = new URL("http://ip.ws.126.net/ipquery?ip="+ip);
HttpURLConnection httpUrl = (HttpURLConnection)url.openConnection();
httpUrl.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
ScriptEngine js=new ScriptEngineManager().getEngineByName("javascript");
InputStreamReader in = new InputStreamReader(httpUrl.getInputStream(),"GBK");
js.eval(in);
result =js.get("lo")+"-"+js.get("lc");
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2020-年
我已经换成ip2region.db了,这个比纯真IP库要准确一些,速度比接口速度快3倍左右
public static void main(String[] args) {
String ip = "222.85.148.46";
long ip2regionStart = System.currentTimeMillis();
String cityOne = AddressUtil.getCityInfo(ip);
System.out.println("ip2region use time:"+(System.currentTimeMillis() - ip2regionStart) + "ms" +" City:"+cityOne);
long ipws126netStart = System.currentTimeMillis();
String cityTwo = getZone(ip);
System.out.println("ipws126net use time:"+(System.currentTimeMillis() - ipws126netStart) + "ms" +" City:"+cityTwo);
}``
运行结果:
ip2region use time:442ms City:中国|西南|贵州省|贵阳市|电信
ipws126net use time:1403ms City:贵州省-贵阳市
后面发现更好的方法会及时更新