java http请求获取ip地址
时间: 2023-09-10 22:09:30 浏览: 110
您可以使用以下代码来获取客户端的 IP 地址:
```java
import javax.servlet.http.HttpServletRequest;
public String getClientIP(HttpServletRequest 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;
}
```
在使用该方法之前,请确保您的代码在一个 HTTP 请求的上下文中,例如在一个 Servlet 或者 Controller 中。这样您就可以从 HttpServletRequest 对象中获取客户端的 IP 地址。
阅读全文