Here's a simple problem - given two urls, is there some built-in method, or an Apache library that decides whether they are (logically) equal?
For example, these two urls are equal:
http://stackoverflow.com
http://stackoverflow.com/
The equals() method of URL class compares this URL for equality with another URL object. It returns false if the given object is not a URL. If IP address of two different is same, then it considered equivalent host.
The compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value: 0: if (x==y) -1: if (x < y)
Java Integer compare() methodpublic static int compare(int x, int y) Parameter : x : the first int to compare y : the second int to compare Return : This method returns the value zero if (x==y), if (x < y) then it returns a value less than zero and if (x > y) then it returns a value greater than zero.
The equals() method of java. util. Set class is used to verify the equality of an Object with a Set and compare them. The method returns true if the size of both the sets are equal and both contain the same elements.
While URI.equals()
(as well as the problematic URL.equals()
) does not return true
for these specific examples, I think it's the only case where equivalence can be assumed (because there is no empty path in the HTTP protocol).
The URIs http://stackoverflow.com/foo
and http://stackoverflow.com/foo/
can not be assumed to be equivalent.
Maybe you can use URI.equals()
wrapped in a utility method that handles this specific case explicitly.
URL::equals reference
URL urlOne = new URL("http://stackoverflow.com");
URL urlTwo = new URL("http://stackoverflow.com/");
if( urlOne.equals(urlTwo) )
{
// ....
}
Note from docs -
Two URL objects are equal if they have the same protocol, reference equivalent hosts, have the same port number on the host, and the same file and fragment of the file.
Two hosts are considered equivalent if both host names can be resolved into the same IP addresses; else if either host name can't be resolved, the host names must be equal without regard to case; or both host names equal to null.
Since hosts comparison requires name resolution, this operation is a blocking operation.
Note: The defined behavior for equals is known to be inconsistent with virtual hosting in HTTP.
So, instead you should prefer URI::equals reference as @Joachim suggested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With