AddressUtils.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package com.willalp.common.utils.ip;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.willalp.common.config.WillalpConfig;
  4. import com.willalp.common.constant.Constants;
  5. import com.willalp.common.utils.StringUtils;
  6. import com.willalp.common.utils.http.HttpUtils;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import javax.annotation.Resource;
  10. /**
  11. * 获取地址类
  12. *
  13. * @author willalp
  14. */
  15. public class AddressUtils {
  16. private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
  17. @Resource
  18. private HttpUtils httpUtils;
  19. // IP地址查询
  20. public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
  21. // 未知地址
  22. public static final String UNKNOWN = "XX XX";
  23. public String getRealAddressByIP(String ip) {
  24. String address = UNKNOWN;
  25. // 内网不查询
  26. if (IpUtils.internalIp(ip)) {
  27. return "内网IP";
  28. }
  29. if (WillalpConfig.isAddressEnabled()) {
  30. try {
  31. String rspStr = httpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK);
  32. if (StringUtils.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. }