0%

Spring Boot 取接口请求IP

首先我们要取得 HttpServletRequest (HttpServletResponse同理)

方式一:通过静态方法获取,也可以封装一个静态方法出来

1
2
3
4
5
6
7
public class HttpContextUtils
{
public static HttpServletRequest getHttpServletRequest()
{
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}

方式二:通过参数直接获取,只要在你的方法上加上参数,SpringBoot 就会帮你绑定,你可以直接使用。如果你的方法有其他参数,把 request 参数加到后面即可

1
2
@GetMapping("/one")
public void methodOne(@RequestParam String name, HttpServletRequest request) { }

方式三:注入到类,这样就不用每个方法都写了

1
2
3
4
5
6
7
8
9
10
private final HttpServletRequest request;

public TestController(HttpServletRequest request)
{
this.request = request;
}

@Log("执行方法一")
@GetMapping("/one")
public void methodOne(@RequestParam String name) { }

拿到 HttpServletRequest 后即可取得请求的 IP 地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class IPUtils
{
/**
* 获取IP地址
* <p>
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(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.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
}
-------------The End-------------
坚持原创技术分享,您的支持将鼓励我继续创作!