UserAgentUtils使用
maven依赖
<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;
}