java_获取指定ip的定位
Posted lavender-pansy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java_获取指定ip的定位相关的知识,希望对你有一定的参考价值。
因为自己网站后台做了一个进站ip统计,之前只是获取了ip,这次优化了下,把ip的大致区域弄出来了
废话不多说,进正题
首先要用到几个网络大头的api
淘宝API:http://ip.taobao.com/service/getIpInfo.php?ip=218.192.3.42
新浪API:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=218.192.3.42
pconline API:http://whois.pconline.com.cn/
百度API:http://api.map.baidu.com/location/ip?ip=218.192.3.42
接下来用json解析返回的数据就好
下面直接上解析源码(不是网站的源码,是之前java测试的源码,原理一样)
package exe; import net.sf.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; /** * 通过淘宝的API来获取指定IP的定位 */ /** * 各种API接口 * 淘宝API:http://ip.taobao.com/service/getIpInfo.php?ip=218.192.3.42 * 新浪API:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=218.192.3.42 * pconline API:http://whois.pconline.com.cn/ * 百度API:http://api.map.baidu.com/location/ip?ip=218.192.3.42 */ public class get_analyse_ip { /** * 涉及到解析json */ public static void main(String[] args) { HttpURLConnection connection ; String api = "http://ip.taobao.com/service/getIpInfo.php"; String connect_symbol = "?"; String front_name = "ip="; Scanner sc = new Scanner(System.in); String real_ip = sc.next(); URL url ; BufferedReader bf ; StringBuffer sb = new StringBuffer(); try { url = new URL(api+connect_symbol+front_name+real_ip); connection = (HttpURLConnection)url.openConnection(); bf = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8")); String line = ""; while(null!=(line = bf.readLine())){ sb.append(line); } } catch (IOException e) { e.printStackTrace(); } // System.out.println(sb); JSONObject dataObject = JSONObject.fromObject(sb.toString()); JSONObject jsonObject= dataObject.getJSONObject("data"); System.out.println(jsonObject.toString()); System.out.println("ip:"+jsonObject.get("ip")); System.out.println("country:"+jsonObject.get("country")); System.out.println("area:"+jsonObject.get("area")); System.out.println("region:"+jsonObject.get("region")); System.out.println("county:"+jsonObject.get("county")); System.out.println("isp:"+jsonObject.get("isp"));
System.out.println("city:"+jsonObject.get("city")); System.out.println("country_id:"+jsonObject.get("country_id")); System.out.println("area_id:"+jsonObject.get("area_id")); System.out.println("region_id:"+jsonObject.get("region_id")); System.out.println("city_id:"+jsonObject.get("city_id")); System.out.println("county_id:"+jsonObject.get("county_id")); System.out.println("isp_id:"+jsonObject.get("isp_id")); } }
要导入json第三方jar包,方法自行百度,在此不赘述
希望对大家有所帮助
以上
以上是关于java_获取指定ip的定位的主要内容,如果未能解决你的问题,请参考以下文章
java_函数手册_String_1.2_codePointCount_获取指定范围文本代码点