Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two URLs in java?

Tags:

java

http

url

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/
like image 431
r0u1i Avatar asked Mar 23 '11 08:03

r0u1i


People also ask

How do I compare two urls?

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.

What is compare () in Java?

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)

How do you compare two values in Java?

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.

How do you compare two sets of elements in Java?

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.


2 Answers

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.

like image 152
Joachim Sauer Avatar answered Sep 23 '22 12:09

Joachim Sauer


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.

like image 28
Mahesh Avatar answered Sep 19 '22 12:09

Mahesh