Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing URLs with parameters in Java

Tags:

java

url

selenium

These two urls should be the same:

http://localhost?asdf=1&qwer=2
http://localhost?qwer=2&asdf=1

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)

like image 412
zorglub76 Avatar asked Sep 19 '12 08:09

zorglub76


People also ask

How to compare two URLs in Java?

Java URL equals() Method 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.


1 Answers

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.

like image 120
S.L. Barth Avatar answered Oct 23 '22 16:10

S.L. Barth