通过ip获取国家 省份 城市信息

添加pom坐标


    com.maxmind.geoip2
    geoip2
    2.15.0

代码

public static void main(String[] args) throws IOException, GeoIp2Exception {
        InputStream inputStream = new FileInputStream(new File("src/main/resources/templates/ip.txt"));
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        // 创建 GeoLite2 数据库
        File database = new File("src/main/resources/templates/GeoLite2-City.mmdb");
        // 读取数据库内容

        DatabaseReader reader = new DatabaseReader.Builder(database).build();


        String str = null;
        while((str = bufferedReader.readLine()) != null)
        {
            try {

                InetAddress ipAddress = InetAddress.getByName(str);
                // 获取查询结果
                CityResponse response = reader.city(ipAddress);

                /*// 获取省份
                Subdivision subdivision = response.getMostSpecificSubdivision();
                System.out.printf(str + "\t" + subdivision.getNames().get("zh-CN") + "\n"); // '广西壮族自治区'*/

                // 获取国家信息
                Country country = response.getCountry();
                System.out.println(country.getIsoCode());               // 'CN'
                System.out.println(country.getName());                  // 'China'
                System.out.println(country.getNames().get("zh-CN"));    // '中国'

                // 获取省份
                Subdivision subdivision = response.getMostSpecificSubdivision();
                System.out.println(subdivision.getName());   // 'Guangxi Zhuangzu Zizhiqu'
                System.out.println(subdivision.getIsoCode()); // '45'
                System.out.println(subdivision.getNames().get("zh-CN")); // '广西壮族自治区'

                // 获取城市
                City city = response.getCity();
                System.out.println(city.getName()); // 'Nanning'
                Postal postal = response.getPostal();
                System.out.println(postal.getCode()); // 'null'
                System.out.println(city.getNames().get("zh-CN")); // '南宁'
                Location location = response.getLocation();
                System.out.println(location.getLatitude());  // 22.8167

            } catch (Exception e) {

            }
        }

        inputStream.close();
        bufferedReader.close();
    }

GeoLite2-City.mmdb该文件需要自行下载,如需要也可私信我

你可能感兴趣的:(学习内容输出,java)