AddressUtils.java 1.7 KB

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