java获取请求接口的ip
时间: 2023-08-13 14:04:21 浏览: 89
java 获取服务器真实IP的实例
要获取请求接口的IP,可以使用Java的Servlet API中的HttpServletRequest对象的getRemoteAddr()方法。这个方法返回客户端的IP地址,也就是请求接口的IP地址。
下面是一个示例代码:
```java
import javax.servlet.http.HttpServletRequest;
public class RequestUtils {
public static String getClientIp(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();
}
return ipAddress;
}
}
```
在Servlet或者Controller层,通过HttpServletRequest对象调用getClientIp方法即可获取请求接口的IP。
```java
@RequestMapping("/test")
public String test(HttpServletRequest request) {
String ip = RequestUtils.getClientIp(request);
// ...
}
```
阅读全文