版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aimeimeiTS/article/details/83625119
背景:根据 HttpServletRequest
获取访问设备信息。
Http 协议请求头中的 User-Agent
属性会将客户端设备的信息传递给服务器,这些信息包括客户端操作系统及版本、CPU 类型、浏览器及版本、浏览器渲染引擎、浏览器语言、浏览器插件等。
参考: 用户代理(User-Agent)
然而客户端设备种类、操作系统及其版本繁多,使得 User-Agent 参数的值也有很多种可能。庆幸的是已经有类库对 User-Agent 的解析做了封装。
<!-- https://mvnrepository.com/artifact/eu.bitwalker/UserAgentUtils -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
</dependency>
在 java 后端项目中可从 HttpServletRequest 中获取 User-Agent 参数值,再借助 UserAgentUtils 工具可以很方便的进行解析。
public static String getDeviceType() {
// ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String agentString = ServletUtil.getRequest().getHeader("User-Agent");
UserAgent userAgent = UserAgent.parseUserAgentString(agentString);
OperatingSystem operatingSystem = userAgent.getOperatingSystem(); // 操作系统信息
eu.bitwalker.useragentutils.DeviceType deviceType = operatingSystem.getDeviceType(); // 设备类型
switch (deviceType) {
case COMPUTER:
return "PC";
case TABLET: {
if (agentString.contains("Android")) return "Android Pad";
if (agentString.contains("iOS")) return "iPad";
return "Unknown";
}
case MOBILE: {
if (agentString.contains("Android")) return "Android";
if (agentString.contains("iOS")) return "IOS";
return "Unknown";
}
default:
return "Unknown";
}
}
DeviceType
为枚举类型,定义了电脑、手机、平板、数字媒体(Google TV)等。
OperatingSystem
中则定义了各种操作系统的关键字,用于解析 User-Agent 参数。