检测 Web 应用程序中的设备类型

2022-09-01 07:20:58

我们有一个基于Java的应用程序,我们希望检测发送请求的设备的设备类型(移动或桌面)。

这怎么可能?


答案 1

您必须从请求中读取标头并做出决定。User-Agent

在 vanilla servlet 应用程序中,一种粗暴的方法是:

public void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
  if(request.getHeader("User-Agent").contains("Mobi")) {
    //you're in mobile land
  } else {
    //nope, this is probably a desktop
  }
}

答案 2

您可以通过解析 http 标头来获取设备信息

String browserType = request.getHeader("User-Agent");

您应该解析 browserType 以获取设备类型

这可能会有所帮助

  public String  getBrowserInfo( String Information )
  {
    String browsername = "";
    String browserversion = "";
    String browser = Information;
    if (browser.contains("MSIE"))
    {
      String subsString = browser.substring(browser.indexOf("MSIE"));
      String info[] = (subsString.split(";")[0]).split(" ");
      browsername = info[0];
      browserversion = info[1];
    } else if (browser.contains("Firefox"))
    {

      String subsString = browser.substring(browser.indexOf("Firefox"));
      String info[] = (subsString.split(" ")[0]).split("/");
      browsername = info[0];
      browserversion = info[1];
    } else if (browser.contains("Chrome"))
    {

      String subsString = browser.substring(browser.indexOf("Chrome"));
      String info[] = (subsString.split(" ")[0]).split("/");
      browsername = info[0];
      browserversion = info[1];
    } else if (browser.contains("Opera"))
    {

      String subsString = browser.substring(browser.indexOf("Opera"));
      String info[] = (subsString.split(" ")[0]).split("/");
      browsername = info[0];
      browserversion = info[1];
    } else if (browser.contains("Safari"))
    {

      String subsString = browser.substring(browser.indexOf("Safari"));
      String info[] = (subsString.split(" ")[0]).split("/");
      browsername = info[0];
      browserversion = info[1];
    }
    return browsername + "-" + browserversion;
  }