前言:
为了更精准的捕获用户访问类型,对用户的行为进行捕获和分析,同时也为了更少的对现有接口进行改动和兼容,我们需要识别接口请求来源于pc设备还是移动端设备。
1、正则表达式
static String phoneDevicesReg = "\\b(ip(hone|od)|android|opera m(ob|in)i"
+"|windows (phone|ce)|blackberry"
+"|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
+"|laystation portable)|nokia|fennec|htc[-_]"
+"|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
static String tableDevicesReg = "\\b(ipad|tablet|(Nexus 7)|up.browser"
+"|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
//移动设备手机端正则匹配
static Pattern phoneDevicesPat = Pattern.compile(phoneDevicesReg, Pattern.CASE_INSENSITIVE);
//移动设备平板端正则匹配
static Pattern tableDevicesPat = Pattern.compile(tableDevicesReg, Pattern.CASE_INSENSITIVE);
2、对移动设备识别标记
public static boolean mobileDevices(HttpServletRequest request){
String userAgent = request.getHeader("USER-AGENT").toLowerCase();
if(null == userAgent){
userAgent = "";
}
// 匹配
Matcher matcherDevicesPhone = phoneDevicesPat.matcher(userAgent);
Matcher matcherDevicesTable = tableDevicesPat.matcher(userAgent);
return (matcherDevicesPhone.find() || matcherDevicesTable.find());
}