How can I get client information such as OS and browser

JavaServlets

Java Problem Overview


I'm using JSP, Servlet to develop my web application.

I want to get client information such as: operation system, browser, resolution, ... whenever a client is using my website.

Java Solutions


Solution 1 - Java

Your best bet is User-Agent header. You can get it like this in JSP or Servlet,

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

The header looks like this,

User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13

It provides detailed information on browser. However, it's pretty much free format so it's very hard to decipher every single one. You just need to figure out which browsers you will support and write parser for each one. When you try to identify the version of browser, always check newer version first. For example, IE6 user-agent may contain IE5 for backward compatibility. If you check IE5 first, IE6 will be categorized as IE5 also.

You can get a full list of all user-agent values from this web site,

http://www.user-agents.org/

With User-Agent, you can tell the exact version of the browser. You can get a pretty good idea on OS but you may not be able to distinguish between different versions of the same OS, for example, Windows NT and 2000 may use same User-Agent.

There is nothing about resolution. However, you can get this with Javascript on an AJAX call.

Solution 2 - Java

In Java there is no direct way to get browser and OS related information.

But to get this few third-party tools are available.

Instead of trusting third-party tools, I suggest you to parse the user agent.

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

By doing this you can separate the browser details and OS related information easily according to your requirement. PFB the snippet for reference (you can replace this with a switch case as well).

        String  browserDetails  =   request.getHeader("User-Agent");
	    String 	userAgent 		= 	browserDetails;
	    String 	user 			= 	userAgent.toLowerCase();
	
        String os = "";
        String browser = "";

		log.info("User Agent for the request is===>"+browserDetails);
		//=================OS=======================
	     if (userAgent.toLowerCase().indexOf("windows") >= 0 )
	     {
	    	 os = "Windows";
	     } else if(userAgent.toLowerCase().indexOf("mac") >= 0)
	     {
	    	 os = "Mac";
	     } else if(userAgent.toLowerCase().indexOf("x11") >= 0)
	     {
	    	 os = "Unix";
	     } else if(userAgent.toLowerCase().indexOf("android") >= 0)
	     {
	    	 os = "Android";
	     } else if(userAgent.toLowerCase().indexOf("iphone") >= 0)
	     {
	    	 os = "IPhone";
	     }else{
	    	 os = "UnKnown,	More-Info: "+userAgent;
	     }
	     //===============Browser===========================
        if (user.contains("msie"))
	    {
	    	String substring=userAgent.substring(userAgent.indexOf("MSIE")).split(";")[0];
	    	browser=substring.split(" ")[0].replace("MSIE", "IE")+"-"+substring.split(" ")[1];
	    } else if (user.contains("safari") && user.contains("version"))
	    {
	    	browser=(userAgent.substring(userAgent.indexOf("Safari")).split(" ")[0]).split("/")[0]+"-"+(userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
	    } else if ( user.contains("opr") || user.contains("opera"))
	    {
	    	if(user.contains("opera"))
	    		browser=(userAgent.substring(userAgent.indexOf("Opera")).split(" ")[0]).split("/")[0]+"-"+(userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
	    	else if(user.contains("opr"))
	    		browser=((userAgent.substring(userAgent.indexOf("OPR")).split(" ")[0]).replace("/", "-")).replace("OPR", "Opera");
	    } else if (user.contains("chrome"))
	    {
	    	browser=(userAgent.substring(userAgent.indexOf("Chrome")).split(" ")[0]).replace("/", "-");
	    } else if ((user.indexOf("mozilla/7.0") > -1) || (user.indexOf("netscape6") != -1)  || (user.indexOf("mozilla/4.7") != -1) || (user.indexOf("mozilla/4.78") != -1) || (user.indexOf("mozilla/4.08") != -1) || (user.indexOf("mozilla/3") != -1) )
	    {
	    	//browser=(userAgent.substring(userAgent.indexOf("MSIE")).split(" ")[0]).replace("/", "-");
	    	browser = "Netscape-?";
	    		  
	    } else if (user.contains("firefox"))
	    {
	    	browser=(userAgent.substring(userAgent.indexOf("Firefox")).split(" ")[0]).replace("/", "-");
	    } else if(user.contains("rv"))
        {
            browser="IE-" + user.substring(user.indexOf("rv") + 3, user.indexOf(")"));
        } else
	    {
	    	browser = "UnKnown,	More-Info: "+userAgent;
	    }
	    log.info("Operating System======>"+os);
	    log.info("Browser Name==========>"+browser);
	    
	

Solution 3 - Java

Update: The project is EOL and not maintained anymore. He recommends switching to the Browscap project.

You can use the bitwalker useragentutils library: https://github.com/HaraldWalker/user-agent-utils. It will provide you information about the Browser (name, type, version, manufacturer, etc.) and about the OperatingSystem. A good thing about it is that it is maintained. Access the link that I have provided to see the Maven dependency that you need to add to you project in order to use it.

See below sample code that returns the browser name and browser version.

	UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
	Browser browser = userAgent.getBrowser();

	String browserName = browser.getName();
	//or 
	// String browserName = browser.getGroup().getName();
	Version browserVersion = userAgent.getBrowserVersion();
	System.out.println("The user is using browser " + browserName + " - version " + browserVersion);

Solution 4 - Java

The browser sends this information in the HTTP header. See the snoop example of Tomcat for some code (source, online demo).

Note that this information is not reliable. Browser can and do lie about who they are and what OS they run on.

Solution 5 - Java

There are two not bad libs for parsing user agent strings:

Solution 6 - Java

You can use browscap-java to get browser's information.

For Example:

UserAgentParser parser = new UserAgentService().loadParser(Arrays.asList(BrowsCapField.BROWSER));
    Capabilities capabilities = parser.parse(user_agent);

    String browser = capabilities.getBrowser();

Solution 7 - Java

Here's my code that works, as of today, with some of the latest browsers.

Naturally, it will break as User-Agent's evolve, but it's simple, and easy to fix.

    String userAgent = "Unknown";
    String osType = "Unknown";
    String osVersion = "Unknown";
    String browserType = "Unknown";
    String browserVersion = "Unknown";
    String deviceType = "Unknown";
    
    try {
        userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165";
        //userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0";
        //userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36";
        //userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134";
        //userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Mobile/15E148 Safari/604.1";
        boolean exceptionTest = false;
        if(exceptionTest) throw new Exception("EXCEPTION TEST");

        if (userAgent.indexOf("Windows NT") >= 0) {
            osType = "Windows";
            osVersion = userAgent.substring(userAgent.indexOf("Windows NT ")+11, userAgent.indexOf(";"));
            
        } else if (userAgent.indexOf("Mac OS") >= 0) {
            osType = "Mac";
            osVersion = userAgent.substring(userAgent.indexOf("Mac OS ")+7, userAgent.indexOf(")"));
            
            if(userAgent.indexOf("iPhone") >= 0) {
                deviceType = "iPhone";
            } else if(userAgent.indexOf("iPad") >= 0) {
                deviceType = "iPad";
            }
            
        } else if (userAgent.indexOf("X11") >= 0) {
            osType = "Unix";
            osVersion = "Unknown";
            
        } else if (userAgent.indexOf("android") >= 0) {
            osType = "Android";
            osVersion = "Unknown";
        }
        logger.trace("end of os section");
        
        if (userAgent.contains("Edge/")) {
            browserType = "Edge";
            browserVersion = userAgent.substring(userAgent.indexOf("Edge")).split("/")[1];

        } else if (userAgent.contains("Safari/") && userAgent.contains("Version/")) {
            browserType = "Safari";
            browserVersion = userAgent.substring(userAgent.indexOf("Version/")+8).split(" ")[0];

        } else if (userAgent.contains("OPR/") || userAgent.contains("Opera/")) {
            browserType = "Opera";
            browserVersion = userAgent.substring(userAgent.indexOf("OPR")).split("/")[1];

        } else if (userAgent.contains("Chrome/")) {
            browserType = "Chrome"; 
            browserVersion = userAgent.substring(userAgent.indexOf("Chrome")).split("/")[1];
            browserVersion = browserVersion.split(" ")[0];

        } else if (userAgent.contains("Firefox/")) {
            browserType = "Firefox"; 
            browserVersion = userAgent.substring(userAgent.indexOf("Firefox")).split("/")[1];
        }            
        logger.trace("end of browser section");
        
    } catch (Exception ex) {
        logger.error("ERROR: " +ex);            
    }
    
    logger.debug(
              "\n userAgent: " + userAgent
            + "\n osType: " + osType
            + "\n osVersion: " + osVersion
            + "\n browserType: " + browserType
            + "\n browserVersion: " + browserVersion
            + "\n deviceType: " + deviceType
            );

Logger Output:

 userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165
 osType: Windows
 osVersion: 10.0
 browserType: Opera
 browserVersion: 60.0.3255.165
 deviceType: Unknown

Solution 8 - Java

You cannot reliably get this information. The basis of several answers provided here is to examine the User-Agent header of the HTTP request. However, there is no way to know if the information in the User-Agent header is truthful. The client sending the request can write anything in that header. So its content can be spoofed, or not sent at all.

Solution 9 - Java

This code is based on the most voted question but I might be easier to use

public enum OS {

    WINDOWS,
    MAC,
    LINUX,
    ANDROID,
    IPHONE,
    UNKNOWN;

    public static OS valueOf(HttpServletRequest request) {

        final String userAgent = request.getHeader("User-Agent");
        final OS toReturn;

        if (userAgent == null || userAgent.isEmpty()) {
            toReturn = UNKNOWN;
        } else if (userAgent.toLowerCase().contains("windows")) {
            toReturn = WINDOWS;
        } else if (userAgent.toLowerCase().contains("mac")) {
            toReturn = MAC;
        } else if (userAgent.toLowerCase().contains("x11")) {
            toReturn = LINUX;
        } else if (userAgent.toLowerCase().contains("android")) {
            toReturn = ANDROID;
        } else if (userAgent.toLowerCase().contains("iphone")) {
            toReturn = IPHONE;
        } else {
            toReturn = UNKNOWN;
        }

        return toReturn;
    }

}

Solution 10 - Java

else if(user.contains("rv:11.0"))
            {
            	String substring=userAgent.substring(userAgent.indexOf("rv")).split("\\)")[0];
            	browser=substring.split(":")[0].replace("rv", "IE")+"-"+substring.split(":")[1];
            	
            }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChan TeeView Question on Stackoverflow
Solution 1 - JavaZZ CoderView Answer on Stackoverflow
Solution 2 - JavalambodarView Answer on Stackoverflow
Solution 3 - JavaDenisaView Answer on Stackoverflow
Solution 4 - JavaAaron DigullaView Answer on Stackoverflow
Solution 5 - JavatworecView Answer on Stackoverflow
Solution 6 - JavaChetna JoshiView Answer on Stackoverflow
Solution 7 - JavaBobCView Answer on Stackoverflow
Solution 8 - JavaRaedwaldView Answer on Stackoverflow
Solution 9 - JavaTk421View Answer on Stackoverflow
Solution 10 - Java Vishal SomaiyaView Answer on Stackoverflow