You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
2.7 KiB
70 lines
2.7 KiB
package com.hai.common.utils;
|
|
import org.springframework.web.context.request.RequestAttributes;
|
|
import org.springframework.web.context.request.RequestContextHolder;
|
|
|
|
import javax.servlet.http.HttpServletRequest;
|
|
|
|
public class RequestUtils {
|
|
|
|
public static String getIpAddress(HttpServletRequest request) {
|
|
String ip = request.getHeader("X-Forwarded-For");
|
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
|
ip = request.getHeader("Proxy-Client-IP");
|
|
}
|
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
|
ip = request.getHeader("WL-Proxy-Client-IP");
|
|
}
|
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
|
ip = request.getHeader("HTTP_CLIENT_IP");
|
|
}
|
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
|
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
|
}
|
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
|
ip = request.getRemoteAddr();
|
|
}
|
|
} else if (ip.length() > 15) {
|
|
String[] ips = ip.split(",");
|
|
for (int index = 0; index < ips.length; index++) {
|
|
String strIp = ips[index];
|
|
if (!("unknown".equalsIgnoreCase(strIp))) {
|
|
ip = strIp;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return ip;
|
|
}
|
|
|
|
|
|
/**
|
|
* 获取请求的ip
|
|
*/
|
|
public static String getRequestIp() {
|
|
|
|
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
|
|
|
|
// 从获取RequestAttributes中获取HttpServletRequest的信息
|
|
HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
|
|
|
|
String ip = request.getHeader("x-forwarded-for");
|
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
|
ip = request.getHeader("Proxy-Client-IP");
|
|
}
|
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
|
ip = request.getHeader("WL-Proxy-Client-IP");
|
|
}
|
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
|
ip = request.getHeader("HTTP_CLIENT_IP");
|
|
}
|
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
|
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
|
}
|
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
|
ip = request.getRemoteAddr();
|
|
}
|
|
|
|
return ip;
|
|
}
|
|
}
|
|
|