AddressUtils.java 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package com.ruoyi.common.utils.ip;
  2. import cn.hutool.core.net.NetUtil;
  3. import cn.hutool.core.util.StrUtil;
  4. import cn.hutool.http.HttpUtil;
  5. import com.alibaba.fastjson.JSONObject;
  6. import com.ruoyi.common.config.RuoYiConfig;
  7. import com.ruoyi.common.constant.Constants;
  8. import lombok.extern.slf4j.Slf4j;
  9. /**
  10. * 获取地址类
  11. *
  12. * @author ruoyi
  13. */
  14. @Slf4j
  15. public class AddressUtils {
  16. // IP地址查询
  17. public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
  18. // 未知地址
  19. public static final String UNKNOWN = "XX XX";
  20. public static String getRealAddressByIP(String ip) {
  21. String address = UNKNOWN;
  22. // 内网不查询
  23. if (NetUtil.isInnerIP(ip)) {
  24. return "内网IP";
  25. }
  26. if (RuoYiConfig.isAddressEnabled()) {
  27. try {
  28. String rspStr = HttpUtil.createGet(IP_URL)
  29. .body("ip=" + ip + "&json=true", Constants.GBK)
  30. .execute()
  31. .body();
  32. if (StrUtil.isEmpty(rspStr)) {
  33. log.error("获取地理位置异常 {}", ip);
  34. return UNKNOWN;
  35. }
  36. JSONObject obj = JSONObject.parseObject(rspStr);
  37. String region = obj.getString("pro");
  38. String city = obj.getString("city");
  39. return String.format("%s %s", region, city);
  40. } catch (Exception e) {
  41. log.error("获取地理位置异常 {}", ip);
  42. }
  43. }
  44. return address;
  45. }
  46. }