1. 程式人生 > >從 HTTPServletRequest 中根據 User-Agent 獲取訪問裝置資訊

從 HTTPServletRequest 中根據 User-Agent 獲取訪問裝置資訊

背景:根據 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)等。
image.png

OperatingSystem 中則定義了各種作業系統的關鍵字,用於解析 User-Agent 引數。
image.png