获取请求地址,根据请求地址获取地域信息

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Optional;

/**

  • 获取客户端IP

  • @author zlb
    */
    @Component
    @Slf4j
    public class IPAddressUtil {

    private static final String LOCAL_IP = “127.0.0.1”;

    private static final String LOCAL_IPS = " 0:0:0:0:0:0:0:1";

    private static final String REQ_URL = “http://ip.taobao.com/service/getIpInfo.php”;
    /**

    • 最大重试次数
      */
      private static final int MAX_REQEST = 3;
      private static final String COLON;
      private static final String SLASH;
      private static final String COMMA;
      private static final String STR_NONE;

    static {
    COLON = “:”;
    SLASH = “”";
    COMMA = “,”;
    STR_NONE = “”;
    }

    /**

    • 获取IP地址

    • @param request

    • @return
      */
      public String getIpAddress(HttpServletRequest request) {

      String ipAddress = request.getHeader(“x-forwarded-for”);
      if (ipAddress == null || ipAddress.length() == 0 || “unknown”.equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getHeader(“Proxy-Client-IP”);
      }
      if (ipAddress == null || ipAddress.length() == 0 || “unknown”.equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getHeader(“WL-Proxy-Client-IP”);
      }

      if (ipAddress == null || ipAddress.length() == 0 || “unknown”.equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getRemoteAddr();
      if (LOCAL_IP.equals(ipAddress) || LOCAL_IPS.equals(ipAddress)) {
      // 根据网卡取本机配置的IP
      InetAddress inet = null;
      try {
      inet = InetAddress.getLocalHost();
      } catch (UnknownHostException e) {
      e.printStackTrace();
      }
      assert inet != null;
      ipAddress = inet.getHostAddress();
      }
      }
      // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照’,'分割
      if (ipAddress != null && ipAddress.length() > 15) { // “***.***.***.***”.length()
      if (ipAddress.indexOf(COMMA) > 0) {
      ipAddress = ipAddress.substring(0, ipAddress.indexOf(COMMA));
      }
      }
      return ipAddress;
      }

    /**

    • @param content 请求的参数 格式为:name=xxx&pwd=xxx
    • @param encodingString 服务器端请求编码。如GBK,UTF-8等
    • @return
    • @throws UnsupportedEncodingException
      */
      private String getAddresses(String content) {
      // 这里调用pconline的接口
      //http://ip.taobao.com/service/getIpInfo.php
      // 从http://whois.pconline.com.cn取得IP所在的省市区信息
      HashMap paramMap = new HashMap<>();
      paramMap.put(“ip”, content);
      String returnStr = “”;
      int count = 0;
      // 失败重连
      while (true) {
      try {
      returnStr = HttpUtil.get(REQ_URL, paramMap);
      break;
      } catch (Exception e) {
      count++;
      if (count >= MAX_REQEST) {
      throw new Exception(“500”, “The request link failed. The number of failed attempts is {}” + count);
      }
      }
      }
      if (returnStr != null) {
      // 处理返回的省市区信息
      log.info(“省市区信息:{}”, returnStr);
      IpInfo ipInfo = JSONUtil.toBean(returnStr, IpInfo.class);
      return Optional.ofNullable(ipInfo).map(ipInfos -> {
      return ipInfos.getData().getRegion();
      }
      ).orElse(null);

// String[] temp = returnStr.split(COMMA);
// if (temp.length < 3) {
// return “0”;//无效IP,局域网测试
// }
// String region = (temp[5].split(COLON))[1].replaceAll(SLASH, STR_NONE);
// region = UnicodeUtil.toString(region);// 省份

// String country = “”;
// String area = “”;
// // String region = “”;
// String city = “”;
// String county = “”;
// String isp = “”;
// for (int i = 0; i < temp.length; i++) {
// switch (i) {
// case 1:
// // 国家
// country = UnicodeUtil.toString((temp[i].split(COLON))[2].replaceAll(SLASH, STR_NONE));
// break;
// case 3:
// // 地区
// area = UnicodeUtil.toString((temp[i].split(COLON))[1].replaceAll(SLASH, STR_NONE));
// break;
// case 5:
// // 省份
// region = UnicodeUtil.toString((temp[i].split(COLON))[1].replaceAll(SLASH, STR_NONE));
// break;
// case 7:
// // 市区
// city = UnicodeUtil.toString((temp[i].split(COLON))[1].replaceAll(SLASH, STR_NONE));
// break;
// case 9:
// // 地区
// county = UnicodeUtil.toString((temp[i].split(COLON))[1].replaceAll(SLASH, STR_NONE));
// break;
// case 11:
// // ISP公司
// isp = UnicodeUtil.toString((temp[i].split(COLON))[1].replaceAll(SLASH, STR_NONE));
// break;
// default:
// }
// }
// return region;
}
return null;
}

/**
 * unicode 转换成 中文
 *
 * @param theString
 * @return
 */
private static String decodeUnicode(String theString) {
    char aChar;
    int len = theString.length();
    StringBuffer outBuffer = new StringBuffer(len);
    for (int x = 0; x < len; ) {
        aChar = theString.charAt(x++);
        if (aChar == '\\') {
            aChar = theString.charAt(x++);
            if (aChar == 'u') {
                int value = 0;
                for (int i = 0; i < 4; i++) {
                    aChar = theString.charAt(x++);
                    switch (aChar) {
                        case '0':
                        case '1':
                        case '2':
                        case '3':
                        case '4':
                        case '5':
                        case '6':
                        case '7':
                        case '8':
                        case '9':
                            value = (value << 4) + aChar - '0';
                            break;
                        case 'a':
                        case 'b':
                        case 'c':
                        case 'd':
                        case 'e':
                        case 'f':
                            value = (value << 4) + 10 + aChar - 'a';
                            break;
                        case 'A':
                        case 'B':
                        case 'C':
                        case 'D':
                        case 'E':
                        case 'F':
                            value = (value << 4) + 10 + aChar - 'A';
                            break;
                        default:
                            throw new IllegalArgumentException(
                                    "Malformed      encoding.");
                    }
                }
                outBuffer.append((char) value);
            } else {
                if (aChar == 't') {
                    aChar = '\t';
                } else if (aChar == 'r') {
                    aChar = '\r';
                } else if (aChar == 'n') {
                    aChar = '\n';
                } else if (aChar == 'f') {
                    aChar = '\f';
                }
                outBuffer.append(aChar);
            }
        } else {
            outBuffer.append(aChar);
        }
    }
    return outBuffer.toString();
}


/**
 * 根据IP获取城市信息
 *
 * @param ip
 * @return
 */
public String getCity(String ip) {
    return this.getAddresses(ip);
}

// 测试
public static void main(String[] args) {
    IPAddressUtil addressUtils = new IPAddressUtil();
    // 测试ip 219.136.134.157 中国=华南=广东省=广州市=越秀区=电信
    String ip = "219.136.134.157";//   116.252.163.231
    String address = "";
    address = addressUtils.getCity(ip);
    System.out.println(address);
    // 输出结果为:广东省,广州市,越秀区
}

}

映射省市区信息实体:

import lombok.Data;

import java.io.Serializable;

/**

  • @author ZLB

  • @version 1.0.0

  • @date 2019/4/28
    */
    @Data
    public class IpInfo implements Serializable {

    private String code;

    private Datas data;

    @Data
    public class Datas implements Serializable {

     private String ip;
    
     private String country;
    
     private String area;
    
     private String region;
    
     private String city;
    
     private String county;
    
     private String isp;
    
     private String country_id;
    
     private String area_id;
    
     private String region_id;
    
     private String city_id;
    
     private String county_id;
    
     private String isp_id;
    

    }
    }

你可能感兴趣的:(工具类,java应用,小知识)