URI.getHost() returns 空

URI.getHost() returns null

这会打印出 null:

System.out.println(new URI("http://a.1a/").getHost());

但这会打印出 a.1a:

System.out.println(new URL("http://a.1a/").getHost());

如果所有 URL 都是 URI(但并非所有 URI 都是 URL),则具有主机组件的有效 URL 不应也具有相同的主机组件(而不是 null) 作为 URI?

查看 Javadoc:

https://docs.oracle.com/javase/8/docs/api/java/net/URI.html:

Returns: The host component of this URI, or null if the host is undefined"

好的,为什么您的特定 URI ("http://a.1a/") 的主机部分未定义?查看 RFC:

https://www.ietf.org/rfc/rfc2396.txt

Hostnames take the form described in Section 3 of [RFC1034] and
Section 2.1 of [RFC1123]: a sequence of domain labels separated by
".", each domain label starting and ending with an alphanumeric
character and possibly also containing "-" characters. The rightmost domain label of a fully qualified domain name will never start > with a digit... To actually be "Uniform" as a resource locator, a URL hostname should be a fully qualified domain name.