首页 > 其他 > 详细

获取请求头中User-Agent工具类

时间:2019-12-17 23:01:28      阅读:123      评论:0      收藏:0      [点我收藏+]
public class AgentUserKit {
    private static String pattern = "^Mozilla/\\d\\.\\d\\s+\\(+.+?\\)";
    private static String pattern2 = "\\(+.+?\\)";
    private static Pattern r = Pattern.compile(pattern);
    private static Pattern r2 = Pattern.compile(pattern2);

    public static String getDeviceInfo(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent==null){
            return null;
        }
        return getDeviceInfo(userAgent);
    }

    private static String getDeviceInfo(String userAgent) {
        String result=null;
        try {
            Matcher m = r.matcher(userAgent);
            if (m.find()) {
                result = m.group(0);
            }
            Matcher m2 = r2.matcher(result);
            if (m2.find()) {
                result = m2.group(0);
            }
            result = result.replace("(", "");
            result = result.replace(")", "");

        } catch (Exception e) {
            return userAgent;
        }
        return filterDeviceInfo(result);
    }

    public static String filterDeviceInfo(String result) {
        if (StringUtils.isEmpty(result)) {
            return null;
        }
        result = result.replace(" U;", "");
        result = result.replace(" zh-cn;", "");
        return result;
    }
}

获取请求头中User-Agent工具类

原文:https://www.cnblogs.com/gabriel-y/p/12057125.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!