java通过浏览器请求头(User-Agent)获取访问者设备信息以及系统版本

/ 2 条评论 / 1414人阅读

在开发AutuBlog项目时需要做后台的登录记录,想起浏览器的User-Agent,于是尝试从浏览器的请求头中获取一些有用的信息。

通过总结大量请求头数据写出以下正则

^Mozilla/\d\.\d\s+\(+.+?\)

该正则含义为

    以Mozilla/开头+浏览器版本格式为数字.数字+空格+(+任意字符串+匹配第一个) 

测试数据

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36

Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:36.0) Gecko/20100101 Firefox/36.0

Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36

经测试可以顺利的获取到设备 以及操作系统信息

完整工具类代码如下

package com.autu.common.kit;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

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");
		return getDeviceInfo(userAgent);
	}

	private static String getDeviceInfo(String userAgent) {
		Matcher m = r.matcher(userAgent);
		String result = null;
		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(")", "");
		return filterDeviceInfo(result);
	}

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

	public static void main(String[] args) {
		System.out.println(getDeviceInfo(
				"Mozilla/5.0 (Linux; U; Android 7.0; zh-cn; MI 5s Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/61.0.3163.128 Mobile Safari/537.36 XiaoMi/MiuiBrowser/10.2.2"));
	}

}
如果有发现不能匹配的请求头欢迎留言


Responses /
  1. alert(1)

    回复
    1. @范文皓

      ces

      回复
    2. @范文皓

      cs

      回复
    3. we
      @范文皓

      we

      回复
  • 回复