Java 识别请求来自移动端还是电脑端

代码:

/**
 * @Author : JCccc
 * @CreateTime : 2020/7/1
 * @Description :
 **/
public class DiscernRequestUtil {
    /**
     * 识别请求是 手机端(分系统) 还是电脑端
     * @param userAgent
     * @return
     */
    public static String getRequestDevice(String userAgent) {
        userAgent=userAgent.toLowerCase();
        if (userAgent.contains("windows phone")){
            return  "Windows手机端";
        }else if (userAgent.contains("android")) {
            return  "安卓手机端";
        }else if(userAgent.contains("iphone") || userAgent.contains("ipad")){
            return  "ios手机端";
        }else {
            return  "电脑端";

        }
    }

    /**
     * 识别请求是手机端还是电脑端
     * @param userAgent
     * @return
     */
    public static String getAskType(String userAgent) {
        userAgent=userAgent.toLowerCase();
        if (userAgent.contains("windows phone")
                ||
                userAgent.contains("android")
                ||
                userAgent.contains("iphone")
                ||
                userAgent.contains("ipad") //暂且把ipad也归为苹果设备
        ){
            return  "mobile";
        }else {
            return  "pc";

        }
    }

}

 

接口测试&使用方式:

就是从HttpServletRequest request 的头里拿出 user-agent 这个key的值做识别处理。

    @GetMapping("doSomeTest")
    public void doSomeTest(HttpServletRequest request){
        
        
        String userAgent  = request.getHeader("user-agent");
        
        
        String requestDevice = getRequestDevice(userAgent);
        System.out.println(requestDevice);

        
        String askType = getAskType(userAgent);
        System.out.println(askType);

    }

 

 

posted on 2022-11-08 07:34  小目标青年  阅读(3)  评论(0编辑  收藏  举报