• notice
  • Congratulations on the launch of the Sought Tech site

Java judges whether it is a mobile or PC request

Mainly judged based on User-Agent

relevant verification

Web side
insert image description here
app side
insert image description here

tool method

/**
  * @author godissleepy
  */
public class StringUtil {
/**
* Defines all possible types of mobile requests
*/
private final static String[] agent = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };

/**
* Determine whether the User-Agent is from a mobile phone
* @param ua
* @return
*/
public static boolean checkAgentIsMobile(String ua) {
boolean flag = false;
if (!ua. contains("Windows NT") || (ua. contains("Windows NT") && ua. contains("compatible; MSIE 9.0;"))) {
// exclude Apple desktop system
if (!ua. contains("Windows NT") && !ua. contains("Macintosh")) {
for (String item: agent) {
if (ua. contains(item)) {
flag = true;
break;
}
}
}
}
return flag;
}

}

Authentication method

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
  * Determine whether it is an app request or a web request
  * @author godissleepy
  */
@RestController
public class RedBagController {

     @GetMapping("/checkAgent")
     public void testUa(HttpServletRequest request, HttpServletResponse response) throws IOException {
         String ua = request. getHeader("User-Agent");
         if(StringUtil. checkAgentIsMobile(ua)){
             System.out.println("app");
         }else{
             System.out.println("web");
         }

     }
}


Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+