正如我在评论中所说,您必须在检查 URL 之前对其进行规范化,并且规范化取决于您的应用程序,因为www.google.com
它不是绝对 URL。这是一个示例代码,可用于检查 URL 是否是绝对的:
import java.net.URL;
public class Test {
public static void main(String [] args) throws Exception {
String [] urls = {"www.google.com",
"http://www.google.com",
"/search",
"file:/dir/file",
"file://localhost/dir/file",
"file:///dir/file"};
for (String url : urls) {
System.out.println("`" + url + "' is " +
(isAbsoluteURL(url)?"absolute":"relative"));
}
}
public static boolean isAbsoluteURL(String url)
throws java.net.MalformedURLException {
final URL baseHTTP = new URL("http://example.com");
final URL baseFILE = new URL("file:///");
URL frelative = new URL(baseFILE, url);
URL hrelative = new URL(baseHTTP, url);
System.err.println("DEBUG: file URL: " + frelative.toString());
System.err.println("DEBUG: http URL: " + hrelative.toString());
return frelative.equals(hrelative);
}
}
输出:
~$ java Test 2>/dev/null
`www.google.com' is relative
`http://www.google.com' is absolute
`/search' is relative
`file:/dir/file' is absolute
`file://localhost/dir/file' is absolute
`file:///dir/file' is absolute