以下是一个示例代码,它使用了 HttpServletRequest 对象来读取 HTTP 头部信息,并使用正则表达式来判断设备类型:
```java
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;
public class DeviceUtils {
private static final String[] mobileUserAgent = { "iphone", "android", "phone", "mobile", "wap", "netfront", "java", "opera mobi", "opera mini", "ucweb", "windows ce", "symbian", "series", "webos", "sony", "blackberry", "dopod", "nokia", "samsung", "palmsource", "xda", "pieplus", "meizu", "midp", "cldc", "motorola", "foma", "docomo", "up.browser", "up.link", "blazer", "helio", "hosin", "huawei", "novarra", "coolpad", "webos", "techfaith", "palmsource", "alcatel", "amoi", "ktouch", "nexian", "ericsson", "philips", "sagem", "wellcom", "bunjalloo", "maui", "smartphone", "iemobile", "spice", "bird", "zte-", "longcos", "pantech", "gionee", "portalmmm", "jig browser", "hiptop", "benq", "haier", "^lct", "320x320", "240x320", "176x220" };
private static final String[] pcHeaders = { "Windows 98", "Windows ME", "Windows 2000", "Windows XP", "Windows NT", "Ubuntu" };
private static final String[] mobileHeaders = { "iPad", "iPhone", "Android", "Pocket", "Sony", "BlackBerry", "WebOS", "HP iPAQ", "Smartphone", "IEMobile", "Windows Phone", "Acer Iconia Tab A500", "Asus Eee Pad Transformer TF101", "Samsung Galaxy Tab", "HTC Flyer" };
private static final String[] botHeaders = { "Googlebot", "Baiduspider", "Yahoo!", "Yahoo Slurp", "DoCoMo", "Sosospider", "Sogou spider", "ia_archiver", "Twiceler" };
public static DeviceType getDeviceType(HttpServletRequest request) {
DeviceType deviceType = DeviceType.UNKNOWN;
String userAgent = request.getHeader("User-Agent");
if (userAgent != null) {
userAgent = userAgent.toLowerCase();
// 匹配
if (Pattern.compile(".*(" + String.join("|", mobileUserAgent) + ").*").matcher(userAgent).matches()) {
deviceType = DeviceType.MOBILE;
} else if (Pattern.compile(".*(" + String.join("|