给定一个字符串,如何确定它是Java中的绝对URL还是相对URL?我尝试了以下代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
问题是所有相对URL都抛出了MalformedURLException,因为没有定义协议(例如:www.google.com和/ questions/ask).