package com.walker.web.agent; import com.walker.web.WebAgentService; import com.walker.web.WebUserAgent; import com.walker.web.util.IpUtils; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; /** * 使用开源组件BrowserCap 实现的解析浏览器代理服务对象。 * @date 2023-01-05 */ public class BrowserCapWebAgentService implements WebAgentService { private Capabilities capabilities = null; private UserAgentParser parser = null; public BrowserCapWebAgentService(){ try { this.parser = new UserAgentService().loadParser(Arrays.asList(BrowsCapField.BROWSER, BrowsCapField.BROWSER_TYPE, BrowsCapField.BROWSER_MAJOR_VERSION, // BrowsCapField.DEVICE_TYPE, BrowsCapField.PLATFORM, BrowsCapField.PLATFORM_VERSION // BrowsCapField.RENDERING_ENGINE_VERSION, BrowsCapField.RENDERING_ENGINE_NAME, // BrowsCapField.PLATFORM_MAKER, BrowsCapField.RENDERING_ENGINE_MAKER )); } catch (Exception e) { throw new RuntimeException("创建浏览器解析对象错误:" + e.getMessage(), e); } } @Override public WebUserAgent getWebUserAgent(String userAgentText, HttpServletRequest request) { WebUserAgent webUserAgent = new WebUserAgent(); if(this.parser == null){ return webUserAgent; } String ip = null; String location = "none"; if(request != null){ ip = IpUtils.getIpAddr(request); if(this.loadLocation){ location = IpUtils.getLocationByIP(ip); } } final Capabilities capabilities = parser.parse(userAgentText); webUserAgent.setBrowserName(capabilities.getBrowser()); webUserAgent.setBrowserVersion(capabilities.getBrowserMajorVersion()); webUserAgent.setDeviceType(capabilities.getDeviceType()); webUserAgent.setOsName(capabilities.getPlatform()); webUserAgent.setOsVersion(capabilities.getPlatformVersion()); webUserAgent.setIp(ip); webUserAgent.setLocation(location); webUserAgent.setMethod(request.getMethod()); webUserAgent.setUrl(request.getRequestURI()); return webUserAgent; } /** * 设置是否加载ip对应的区域地质,默认:false不加载,因为需要连外网查找。 * @param loadLocation * @date 2023-12-11 */ public void setLoadLocation(boolean loadLocation) { this.loadLocation = loadLocation; } private boolean loadLocation = false; }