get Browser Version From User Agent - Java Network

Java examples for Network:User Agent

Description

get Browser Version From User Agent

Demo Code


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

public class Main{
    // www  . j  a va 2 s. c  o  m
    public static String getBrowserVersionFromUserAgent(String userAgent,
            String browser) {
        if (StringUtil.isEmpty(browser))
            return "";
        if (StringUtil.isEmpty(userAgent))
            return "";
        userAgent = userAgent.toLowerCase();
        int length = userAgent.length();
        int begin = -1;

        String versionKey = browser;

        if (browser.equals("safari"))
            versionKey = "version";
        begin = userAgent.indexOf(versionKey);
        if (begin == -1)
            return "";
        begin = begin + versionKey.length();
        int end = begin + 2;
        for (int i = 2; i < 50; i++) {
            if ((begin + i) >= userAgent.length())
                break;
            char value = userAgent.charAt(begin + i);
            if (value == '/' || value == ';' || value == ' ') {
                end = begin + i;
                break;
            }
            if (begin + i == length - 1) {
                end = length;
                break;
            }
        }
        return userAgent.substring(begin + 1, end);
    }
}

Related Tutorials