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

tech2022-10-12  107

代码:

/** * @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); }

 

 

最新回复(0)