JAVA获取ip的地址信息

添加maven依赖

<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.5</version>
        </dependency>

获取IP地址工具类

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * @author lrx
 * @description: TODO
 * @date 2021/11/29 17:43
 */
public class IpAddressUtils {
    /**
     * 根据ip获取地址
     * @param ip
     * @return
     */
    public static String getAddress(String ip) {
        String url = "http://ip.ws.126.net/ipquery?ip=" + ip;
        String str = HttpUtil.get(url);
        if(!StrUtil.hasBlank(str)){
            String substring = str.substring(str.indexOf("{"), str.indexOf("}")+1);
            System.out.println(substring);
            JSONObject jsonObject = JSONUtil.parseObj(substring);
            String province = jsonObject.getStr("province");
            String city = jsonObject.getStr("city");
            return province + " " + city;
        }
        return null;
    }

    public static void main(String[] args) {
        String ip = "183.15.178.242";
        String result = getAddress(ip);
        System.out.println(result);
    }
}

运行查看

{city:"深圳市", province:"广东省"}
广东省 深圳市

posted @ 2022-08-11 18:48  码海兴辰  阅读(320)  评论(0)    收藏  举报