Given a string, how do I determine if it is absolute URL or relative URL in Java? I tried the following code:
private boolean isAbsoluteURL(String urlString)
{
boolean result = false;
try
{
URL url = new URL(urlString);
String protocol = url.getProtocol();
if (protocol != null && protocol.trim().length() > 0)
result = true;
}
catch (MalformedURLException e)
{
return false;
}
return result;
}
The problem is that all relative URLs are throwing the MalformedURLException as there is no protocol defined (example: www.google.com and /questions/ask).
How about:
see for details: http://docs.oracle.com/javase/7/docs/api/java/net/URI.html
HTH
This is a snippet I use to ensure links are absolute:
I made this
As I said i my comment, you have to normalize the URL, before checking it, and that normalization depends on your application, since
www.google.com
is not an absolute URL. Here is an example code, which can be used to check URLs to be absolute:running: