IP定位工具

相关代码

百度IP定位API

IP定位测试接口

/**
 * IPUtils
 *
 * @author 伍磊
 */
public class IpUtils {

    /**
     * 获取请求接口ip地址
     * @return java.lang.String
     */
    public static String getIpAddr() {
        javax.servlet.http.HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("PRoxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 根据ip定位到实际地址 若是定位失败 则返回"-"
     * @param ip ip
     * @return java.lang.String
     */
    public static String getIpAddr(String ip) {
        String ipAddress = Constant.NONE;

        //1 校验
        if (StringUtils.isBlank(ip)) {
            return Constant.NONE;
        }

        //2 设置参数和header
        Map map = new HashMap<>();
        Map headers = new HashMap<>();
        map.put("ip", ip);
        // 设置秘钥
        map.put("ak", Constant.AK_SECRET_KEY);
        headers.put("Content-Type", "application/json;charset=utf-8");

        //3 调用接口
        String response;
        try {
            response = HttpClientExecutor.doPost(Constant.LOCATE_API, headers, map, 2000);
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.error(LogAction.ERROR, "请求根据ip定位具体地址接口时出现异常。。。");
            return ipAddress;
        }

        //4 处理返回
        JSONObject jsonObject = JSONObject.parseObject(response);
        Object status = jsonObject.get("status");
        if (Objects.equals(status, Constant.INT_ZERO)) {
            // 成功响应 处理结果
            String content = jsonObject.get("content").toString();
            JSONObject object = JSONObject.parseObject(content);
            ipAddress = object.get("address").toString();
        }

        return ipAddress;
    }
}


代码相关常量

/**
     * int-0
     */
    public static final Integer INT_ZERO = 0;

    /**
     * -
     */
    public static final String NONE = "-";

    /**
     * ak秘钥 (获取ip地址)
     */
    public static final String AK_SECRET_KEY = "OGNLmlzGl46KE7HU0hblDk2zXPPv0w5v";

    /**
     * 百度接口api (定位ip地址接口)
     */
    public static final String LOCATE_API = "http://api.map.baidu.com/location/ip";

你可能感兴趣的:(IP定位工具)