Given a string, how do I determine if it is an absolute URL or a 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 (www.google.com
or /questions/ask
). are throwing a MalformedURLException
because there is no protocol defined.
/
is an absolute URL forfile:
but it is relative forhttp:
. If you don't know the base URL (acutally, the protocol), you cannot determine the relativeness of the given URL. In your example -www.google.com
is a relative URL, so your method is correct and specification-compliant in this case, but it doesn't solve your problem.