AddressUtils.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package com.ruoyi.common.utils.ip;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.ruoyi.common.constant.Constants;
  6. import com.ruoyi.common.utils.StringUtils;
  7. import com.ruoyi.common.utils.http.HttpUtils;
  8. import com.ruoyi.framework.config.RuoYiConfig;
  9. /**
  10. * 获取地址类
  11. *
  12. * @author ruoyi
  13. */
  14. public class AddressUtils
  15. {
  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. String address = UNKNOWN;
  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 = JSONObject.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 address;
  50. }
  51. }