我尝试编写一些正则表达式来确定客户端设备详细信息,例如操作系统名称、浏览器 daetils 仍然面临 IE 浏览器检测问题。
浏览器检测代码:
public static final BrowserBean getBrowserInfo(String userAgent){
BrowserBean browserBean = new BrowserBean();
Pattern pattern = Pattern.compile("(?i)(opera|chrome|safari|firefox|MSIE|trident)(\\s|\\/)(\\d+.\\d+)");
Matcher matcher = pattern.matcher(userAgent);
while (matcher.find()) {
int groupCount = matcher.groupCount();
if(groupCount >= 3){
browserBean.setBrowserName(matcher.group(1));
browserBean.setBrowserVersion(matcher.group(3));
}
}
return browserBean;
}
测试用例:
@Test
public void detectSafaritest() {
String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.71 (KHTML, like Gecko) Version/6.1 Safari/537.71";
BrowserBean bean = UserAgentDetermination.getBrowserInfo(userAgent);
Assert.assertEquals("Safari", bean.getBrowserName());
Assert.assertEquals("537.71", bean.getBrowserVersion());
}
@Test
public void detectIEtest() {
String userAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; MASP)";
BrowserBean bean = UserAgentDetermination.getBrowserInfo(userAgent);
Assert.assertEquals("InterNet Explorer", bean.getBrowserName());
Assert.assertEquals("10.0", bean.getBrowserVersion());
}
@Test
public void detectFireFoxtest() {
String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0";
BrowserBean bean = UserAgentDetermination.getBrowserInfo(userAgent);
Assert.assertEquals("Firefox", bean.getBrowserName());
Assert.assertEquals("25.0", bean.getBrowserVersion());
}
// @Test
// public void detectOperatest() {
// String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.71 (KHTML, like Gecko) Version/6.1 Safari/537.71";
// BrowserBean bean = UserAgentDetermination.getBrowserInfo(userAgent);
// Assert.assertEquals("Safari", bean.getBrowserName());
// Assert.assertEquals("537.71", bean.getBrowserVersion());
// }
@Test
public void detectChrometest() {
String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36";
BrowserBean bean = UserAgentDetermination.getBrowserInfo(userAgent);
Assert.assertEquals("Chrome", bean.getBrowserName());
Assert.assertEquals("30.0", bean.getBrowserVersion());
}
我遇到了 IE 和 trident 浏览器的问题,因为我可以看到用户代理打印为:Mozilla/5.0(兼容;MSIE 9.0;Windows NT 6.1;WOW64;Trident/5.0;MASP)Mozilla/5.0(Windows NT 6.3; Trident/7.0; rv:11.0) 像壁虎
请帮助我成功识别 IE 所有版本。
如果您也帮助我提供设备信息,我们将不胜感激。