【java】使用ip获取 国家 省份 城市

 1.下载GeoLite2 City库

下载地址:

http://dev.maxmind.com/geoip/geoip2/geolite2/

https://download.csdn.net/download/qq_44065303/20680263

2.导入相关坐标坐标

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>

  3.代码实现

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

/**
 * @author yijiu
 * @date 2021/8/2 15:04
 */
public class IpAddress {

    public static void main(String[] args) throws Exception{

        String ip = "180.117.160.226";
        IpAddress ipAddressController = new IpAddress();
        // 获取国家信息
        String country = ipAddressController.getCountry(ip);
        System.out.println("country:"+country);

        // 获取省份
        String province = ipAddressController.getProvince(ip);
        System.out.println("province:"+province);
        // 获取城市
        String city = ipAddressController.getCity(ip);
        System.out.println("city:"+city);
    }

    private String getCity(String ip) throws IOException, GeoIp2Exception {
        // 创建 GeoLite2 数据库
        File database = new File("GeoLite2-City.mmdb");//这里是下载的GeoLite2 City库的路径
        // 读取数据库内容
        DatabaseReader reader = new DatabaseReader.Builder(database).build();
        InetAddress ipAddress = InetAddress.getByName(ip);
        // 获取查询结果
        CityResponse response = reader.city(ipAddress);
        //获取City
        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
//        System.out.println(location.getLongitude()); // 108.3167
        return city.getNames().get("zh-CN");
    }

    private String getProvince(String ip) throws IOException, GeoIp2Exception {
        // 创建 GeoLite2 数据库
        File database = new File("GeoLite2-City.mmdb");
        // 读取数据库内容
        DatabaseReader reader = new DatabaseReader.Builder(database).build();
        InetAddress ipAddress = InetAddress.getByName(ip);
        // 获取查询结果
        CityResponse response = reader.city(ipAddress);
        //获取Province
        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")); // '广西壮族自治区'
        return subdivision.getNames().get("zh-CN");
    }

    private String getCountry(String ip) throws IOException, GeoIp2Exception {
        // 创建 GeoLite2 数据库
        File database = new File("GeoLite2-City.mmdb");
        // 读取数据库内容
        DatabaseReader reader = new DatabaseReader.Builder(database).build();
        InetAddress ipAddress = InetAddress.getByName(ip);
        // 获取查询结果
        CityResponse response = reader.city(ipAddress);
        //获取country
        Country country = response.getCountry();
//        System.out.println(country.getIsoCode()); // 'CN'
//        System.out.println(country.getName()); // 'China'
//        System.out.println(country.getNames().get("zh-CN")); // '中国'
        return country.getNames().get("zh-CN");
    }
}

输入结果

country:中国
province:江苏省
city:苏州市

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,您可以通过解析JSON数据来获取全国省份城市,然后根据省份名称获取省份城市列表。以下是一个通过省份获取城市列表的例子: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; public class CityByProvinceExample { public static void main(String[] args) { String apiUrl = "http://cdn.cnbj1.fds.api.mi-img.com/mi-mall/5d6d9de8f27ad.json"; String provinceName = "广东省"; // 要获取城市列表的省份名称 try { URL url = new URL(apiUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject jsonObject = new JSONObject(response.toString()); JSONArray provincesArray = jsonObject.getJSONArray("provinces"); List<String> cities = new ArrayList<>(); for (int i = 0; i < provincesArray.length(); i++) { JSONObject provinceObj = provincesArray.getJSONObject(i); String province = provinceObj.getString("name"); if (province.equals(provinceName)) { JSONArray citiesArray = provinceObj.getJSONArray("cities"); for (int j = 0; j < citiesArray.length(); j++) { JSONObject cityObj = citiesArray.getJSONObject(j); String cityName = cityObj.getString("name"); cities.add(cityName); } break; } } System.out.println(cities.toString()); } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码中,我们首先使用阿里巴巴的城市数据API获取JSON格式的城市数据。然后,我们解析JSON数据,查找与给定省份名称相匹配的省份,并获取省份城市列表。最后,我们将城市列表打印出来。请注意,这个例子仅提供了获取城市列表的基本思路,您可以根据需要对其进行更改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值