AddressUtils.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package com.ruoyi.common.utils.ip;
  2. import com.alibaba.fastjson2.JSON;
  3. import com.alibaba.fastjson2.JSONObject;
  4. import com.ruoyi.common.config.RuoYiConfig;
  5. import com.ruoyi.common.constant.Constants;
  6. import com.ruoyi.common.utils.StringUtils;
  7. import com.ruoyi.common.utils.http.HttpUtils;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. /**
  11. * 获取地址类
  12. *
  13. * @author ruoyi
  14. */
  15. public class AddressUtils {
  16. private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
  17. // IP地址查询
  18. public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
  19. // 未知地址
  20. public static final String UNKNOWN = "XX XX";
  21. public static String getRealAddressByIP(String ip) {
  22. // 内网不查询
  23. if (IpUtils.internalIp(ip)) {
  24. return "内网IP";
  25. }
  26. if (RuoYiConfig.isAddressEnabled()) {
  27. try {
  28. String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK);
  29. if (StringUtils.isEmpty(rspStr)) {
  30. log.error("获取地理位置异常 {}", ip);
  31. return UNKNOWN;
  32. }
  33. JSONObject obj = JSON.parseObject(rspStr);
  34. String region = obj.getString("pro");
  35. String city = obj.getString("city");
  36. return String.format("%s %s", region, city);
  37. } catch (Exception e) {
  38. log.error("获取地理位置异常 {}", ip);
  39. }
  40. }
  41. return UNKNOWN;
  42. }
  43. }