SpringBoot-(十五)实现获取请求的IP、浏览器等信息

本文最后更新于:March 14, 2022 pm

SpringBoot框架中有两个非常重要的策略:开箱即用和约定优于配置。其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

目录

导入依赖

1
2
3
4
5
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
</dependency>

工具类

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.tothefor.utils;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
* @Author DragonOne
* @Date 2022/3/13 19:44
* @墨水记忆 www.tothefor.com
*/
public class RequestInfoUtils {
/**
* 获取发起请求的IP地址
*/
public static String getIp(HttpServletRequest request) {
String ip = null;
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();
if (ip.equals("127.0.0.1")) {
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ip = inet.getHostAddress();
}
}
if ((ip != null) && (ip.length() > 15)) {
if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
return ip;
}

/**
* 获取发起请求的浏览器名称
*/
public static String getBrowserName(HttpServletRequest request) {
String header = request.getHeader("User-Agent");
UserAgent userAgent = UserAgent.parseUserAgentString(header);
Browser browser = userAgent.getBrowser();
return browser.getName();
}

/**
* 获取发起请求的浏览器版本号
*/
public static String getBrowserVersion(HttpServletRequest request) {
String header = request.getHeader("User-Agent");
UserAgent userAgent = UserAgent.parseUserAgentString(header);
// 获取浏览器信息
Browser browser = userAgent.getBrowser();
// 获取浏览器版本号
Version version = browser.getVersion(header);
return version.getVersion();
}

/**
* 获取发起请求的操作系统名称
*/
public static String getOsName(HttpServletRequest request) {
String header = request.getHeader("User-Agent");
UserAgent userAgent = UserAgent.parseUserAgentString(header);
OperatingSystem operatingSystem = userAgent.getOperatingSystem();
return operatingSystem.getName();
}
}