Comparing URLs with parameters in Java

java url equals
compare url java

These two urls should be the same:


But using 'equals()' from the URL class, I get that they're different. How can I compare them?

EDIT: Some background on this question

I'm creating a Selenium test for some url mapping. I have old url, url it should get mapped to and the actual url. I need to compare the should-be url to the actual url. List of urls is created by client. Urls with the same parameters and values are considered valid if the list of parameters is the same, and they all have the right values (order of those parameters is irrelevant)

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.

What java library can I use to compare two URLs for equality , will compare two URLs without network requests (the way Servers are allowed to assign meaning to the order of parameters,  You can compare two URL objects by using equals method. Below example shows how to compare two URL objects. The equals() method returns boolean value. If both URL values are same then it returns true, otherwise it returns false.

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()) &&

    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;



            } 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";




    return parameters;


URL sameFile() method in Java with Examples, 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,  Comparing String Objects, intern() & other confusions Decimal Formatting in Java Open default mail application in your machine using Java JFreeChart - A great tool to implement Graphs & Charts in Java Add log4j to RCP application Creating a plug in for Eclipse Adding Commands and Menus in RCP

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

Java URL equals() Method with Examples, sameFile(url2); Parameter: This method accepts a mandatory parameter url which is the second url to be compared to this url. Return Value: This method returns true if both the URL are same excluding the fragment part else returns false. The URL class, along with these accessor methods, frees you from ever having to parse URLs again! Given any string specification of a URL, just create a new URL object and call any of the accessor methods for the information you need. This small example program creates a URL from a string specification and then uses the URL object's accessor

You can accomplish this with functionality available in the String class.

This approach splits the URLs into two parts, the one before the "?" and the one after (it's fine if no "?" or parameters are present). If the URLs before the "?" are equivalent, the two are "equal" for our purposes.

public boolean urlsMatchWithoutQueryParameters(String firstUrl, secondUrl) {
    // Get the portion of the URLs before the "?", and before all parameters.
    String firstUrlWithoutParameters = firstUrl.split("\\?", 2)[0];
    String secondUrlWithoutParameters = secondUrl.split("\\?", 2)[0];

    return firstUrlWithoutParameters.equals(secondUrlWithoutParameters);

The code is a little crowded, so you could do something pull out the String logic into a helper like so:

public boolean urlsMatchWithoutQueryParameters(String firstUrl, secondUrl) {
    return getUrlWithoutParameters(firstUrl).equals(getUrlWithoutParameters(secondUrl));

public String getUrlWithoutParameters(String url) {
    // Get the portion of the URL before the "?", and before all parameters.
    return url.split("\\?", 2)[0];

Note: This ignores URL anchors (e.g., #photos in the url To for anchors, simply replace "\\?" with "#" in split("\\?", 2).

Java Code Examples, Parameter. obj - the URL to compare against. Returns. true if the objects are the same; false otherwise. Example 1. URL class in Java with Examples The URL class is the gateway to any of the resource available on the internet. A Class URL represents a Uniform Resource Locator, which is a pointer to a “resource” on the World Wide Web.

I like this question so I wrote this little demo. (Sorry, I used the StringUtils class for the substrings)

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class URLDemo

     * @param args
     * @throws MalformedURLException
    public static void main(String[] args)
        throws MalformedURLException
        String url1 = "http://localhost?asdf=1&qwer=2";
        String url2 = "http://localhost?qwer=2&asdf=1";
        URL url11 = new URL(StringUtils.substringBefore(url1, "?"));
        URL url22 = new URL(StringUtils.substringBefore(url2, "?"));

        if (url11.equals(url22))
            // url are equal but still need to check the parameters
            List<String> params1 = Arrays.asList(StringUtils.split(StringUtils.substringAfter(url1, "?"), "&"));
            List<String> params2 = Arrays.asList(StringUtils.split(StringUtils.substringAfter(url2, "?"), "&"));

            // need to check both ways
            if (params1.containsAll(params2) && params2.containsAll(params1))
                System.out.println("URLs are the same");
                System.out.println("URLs are different");


Comparing URLs with parameters in Java -, And URLs should not be used for comparison, as written here: /3771081/​proper-way-to-check-for-url-equality * * @param uri1 * URI 1 to be compared. Specifying a handler of null indicates that the URL should use a default stream handler for the protocol, as outlined for:, java.lang.String, int, java.lang.String) If the handler is not null and there is a security manager, the security manager's checkPermission method is called with a NetPermission

URL (Java Platform SE 8 ), i'm creating selenium test url mapping. have old url, url should mapped , actual url. need compare should-be url actual url. list of urls created  Comparator<Person> cmp = Comparator.comparing( Person::getLastName, String.CASE_INSENSITIVE_ORDER); Type Parameters: T - the type of element to be compared U - the type of the sort key Parameters: keyExtractor - the function used to extract the sort key keyComparator - the Comparator used to compare the sort key Returns:

Uri.Compare(Uri, Uri, UriComponents, UriFormat, StringComparison , Returns true if this URL and the other argument are equal without taking the fragment component into consideration. Parameters: other - the URL to compare​  url-difference ===== This class can calculate difference between two Urls. Generally it is difficult to find differences between two long URLs containing key value pairs. You have to "eye-ball" each URL and find difference especially when two urls have different parameters ordering. See example.php for more details.

URL objects, Parameters. uri1: Uri. The first Uri. uri2: Uri. The second Uri. I am using Java 1.6 so I can't really use the Classes that you have said from Java 1.7 also I want to use pure Java for this class without any dependency that's why I cannot use the Guava, that this library is great. I will change the other things as you have mentioned. Again thank you very much. \$\endgroup\$ – Tapas Bose Aug 28 '14 at 13:50

  • These two URL's are different for me (and for many others :)) and that is why equals method in URL class returns false for that. You should write your own method which compares the query parameter and returns result according to that.
  • They are actually the same. The order of the parameters should have no effect on any J2EE application.
  • I'll probably have to do something like this. I really find it hard to believe that there isn't a tested library with such a comparison. I'm always worried about how such code would handle encoding, ending slashes ("localhost/" vs. "localhost") and things like that. I generally hate reinventing the wheels....
  • Note that the parameters are the same, just a different order. I think the question is about that.
  • @S.L.Barth equals() method checks whether the Objects pointed by the Object Reference Variable are same or different, as both the url are different, 2 different objects are created on the heap, so we get that both are simple as that....
  • @KumarVivekMitra equals is overrided... you're not comparing heap addresses there.
  • I get that, but the OP's problem is (apparently) how to find if the URL's are the same modulo the order of parameters. He'll probably need to write his own Comparator.