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.