概述
在软件开发中,经常会遇到需要获取客户端操作系统和版本号等信息的需求。
参考官网
The user-agent-utils java library can be used to parse HTTP requests in real-time or to analyze log files and gather information about the user-agent.
简单翻译:可用于实时解析HTTP请求,也可以用于解析日志文件获取user-agent信息。
引入如下maven依赖,虽然很久没有更新,上次release还是Jan 24, 2018
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
</dependency>
源码组织:
示例:
public static void main(String[] args) {
// org.springframework.web.server.ServerWebExchange
ServerHttpRequest request = exchange.getRequest();
Map<String, String> headers = request.getHeaders().toSingleValueMap();
UserAgent userAgent = UserAgent.parseUserAgentString(headers.get("User-Agent"));
String browser = getBrowser(userAgent.getBrowser().name());
String operatingSystem = getOperatingSystem(userAgent.getOperatingSystem().name());
// com.netflix.zuul.context.RequestContext
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest req = ctx.getRequest();
UserAgent userAgent = UserAgent.parseUserAgentString(req.getHeader("User-Agent"));
Browser browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
Version version = browser.getVersion(request.getHeader("User-Agent"));
}
private String getBrowser(String browser) {
if (StrUtil.isNotEmpty(browser)) {
if (browser.contains("CHROME")) {
return "CHROME";
} else if (browser.contains("FIREFOX")) {
return "FIREFOX";
} else if (browser.contains("SAFARI")) {
return "SAFARI";
} else if (browser.contains("EDGE")) {
return "EDGE";
}
}
return browser;
}
private String getOperatingSystem(String operatingSystem) {
if (StrUtil.isNotEmpty(operatingSystem)) {
if (operatingSystem.contains("MAC_OS_X")) {
return "MAC_OS_X";
} else if (operatingSystem.contains("ANDROID")) {
return "ANDROID";
}
}
return operatingSystem;
}
参考
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/142246.html