GeoIP 全球IP定位 for JAVA 使用说明

GeoLite2 全球IP定位 for JAVA 使用说明

备注:GeoIP 与 GeoLite2 完全相同,两者属于同一产品。

一、下载全球国家/城市IP库

国家IP库:https://download.csdn.net/download/xu_cxiang/12506401(推荐使用本库,体积小,查询速度快)
城市IP库:https://download.csdn.net/download/xu_cxiang/12506391

二、使用maven引入依赖包

<dependency>
   <groupId>com.maxmind.geoip2</groupId>
   <artifactId>geoip2</artifactId>
   <version>2.13.1</version>
</dependency>

三、使用全球 ‘城市’ 离线库进行IP定位。

    public static void main(String[] args) throws IOException, GeoIp2Exception{
    	// 读取离线库,根据文件存放位置自主修改
        File database = new File("/path/to/GeoIP2-City.mmdb");
        DatabaseReader reader = new DatabaseReader.Builder(database).build();
        // 指定获取到的IP地址
        InetAddress ipAddress = InetAddress.getByName("128.101.101.101");
        // 根据ip获取请求
        CityResponse response = reader.city(ipAddress);
        // 获取国家
        Country country = response.getCountry();
        // 获取编码
        System.out.println(country.getIsoCode());            
        System.out.println(country.getName());               
        System.out.println(country.getNames().get("zh-CN")); 
         
        Subdivision subdivision = response.getMostSpecificSubdivision();
        System.out.println(subdivision.getName());    
        System.out.println(subdivision.getIsoCode()); 
         
        City city = response.getCity();
        System.out.println(city.getName()); 
         
        Postal postal = response.getPostal();
        System.out.println(postal.getCode()); 
         
        Location location = response.getLocation();
        System.out.println(location.getLatitude());  
        System.out.println(location.getLongitude());
    }

四、使用全球 ‘国家’ 离线库进行IP定位。

    public static void main(String[] args) throws IOException, GeoIp2Exception{
    	// 读取离线库,根据文件存放位置自主修改
        File database = new File("/path/to/GeoIP2-Country.mmdb");
        DatabaseReader reader = new DatabaseReader.Builder(database).build();
        // 指定获取到的IP地址
        InetAddress ipAddress = InetAddress.getByName("128.101.101.101");
        // 根据ip获取请求
        CityResponse response = reader.country(ipAddress);
        // 获取国家
        Country country = response.getCountry();
        // 获取编码
        System.out.println(country.getIsoCode());            
        System.out.println(country.getName());               
        System.out.println(country.getNames().get("zh-CN")); 
         
        Subdivision subdivision = response.getMostSpecificSubdivision();
        System.out.println(subdivision.getName());    
        System.out.println(subdivision.getIsoCode()); 
         
        City city = response.getCity();
        System.out.println(city.getName()); 
         
        Postal postal = response.getPostal();
        System.out.println(postal.getCode()); 
         
        Location location = response.getLocation();
        System.out.println(location.getLatitude());  
        System.out.println(location.getLongitude());
    }

你可能感兴趣的:(interface)