Comparing URLs with parameters in Java Comparing URLs with parameters in Java selenium selenium

Comparing URLs with parameters in Java


So if I get it right, you want to compare two URL's, regardless of the order of the query part.

There does not seem to be a method for this in the URL class, so you'll have to write your own.Also, URL is final, you cannot override URL.equals(Object).

Your method could start with calling sameFile().
If that evaluates to true, you then call getQuery(), and split it into it's components - probably with String.split("\&"). From there on, you evaluate if the parameters are the same.
Also, don't forget to check if the "#fragment" is equal, if that is important to your application.


I don't think you're going to like it, but you could do something like

URL url = new URL("http://localhost?asdf=1&qwer=2");URL url2 = new URL("http://localhost?qwer=2&asdf=1");System.out.println(isEqual(url, url2));public static boolean isEqual(URL url1, URL url2) {    boolean isEqual = url1.getAuthority().equals(url2.getAuthority()) &&                    url1.getPort() == url2.getPort() &&                    url1.getHost().equals(url2.getHost()) &&                    url1.getProtocol().equals(url2.getProtocol());    if (isEqual) {        String query1 = url1.getQuery();        String query2 = url2.getQuery();        if (query1 != null && query2 != null) {            if (query1.length() == query2.length()) {                List<String> list1 = getParameters(query1);                List<String> list2 = getParameters(query2);                for (int index = 0; index < list1.size(); index++) {                    String value1 = list1.get(index);                    String value2 = list2.get(index);                    if (!value1.equals(value2)) {                        isEqual = false;                        break;                    }                }            } else {                isEqual = false;            }        } else {            isEqual = false;        }    }    return isEqual;}protected static List<String> getParameters(String value) {    List<String> parameters = new ArrayList<String>(25);    String[] values = value.split("&");    for (String par : values) {        if (!par.contains("=")) {            par += "=null";        }        parameters.add(par);    }    Collections.sort(parameters);    return parameters;}


URL/URI equals method is broken. At least it doesn't provide results as you would expect.There are a lot of weird things with it. You might be interested to read

Mr. Gosling – why did you make URL equals suck?!?

or maybe

How to compare two URLs in java?

So, don't expect it would be easy.You can create your custom comparator for your particular case but in general you might have to parse the url string.

Hope this helps