主机名必须符合以下语法:
hostname = domainlabel [ "." ] | 1*( domainlabel "." ) toplabel [ "." ]
domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
toplabel = alpha | alpha *( alphanum | "-" ) alphanum
正如您所看到的,只允许使用.
和-
,不允许使用_
。
然后您说//5-12-145-35_s-81:443
是允许的,确实如此,但不适用于主机名。
为了了解情况如何发展:
URI uriBadHost = URI.create("//5-12-145-35_s-81:443");
System.out.println("uri = " + uriBadHost);
System.out.println(" authority = " + uriBadHost.getAuthority());
System.out.println(" host = " + uriBadHost.getHost());
System.out.println(" port = " + uriBadHost.getPort());
URI uriGoodHost = URI.create("//example.com:443");
System.out.println("uri = " + uriGoodHost);
System.out.println(" authority = " + uriGoodHost.getAuthority());
System.out.println(" host = " + uriGoodHost.getHost());
System.out.println(" port = " + uriGoodHost.getPort());
输出
uri = //5-12-145-35_s-81:443
authority = 5-12-145-35_s-81:443
host = null
port = -1
uri = //example.com:443
authority = example.com:443
host = example.com
port = 443
正如您所看到的,当
authority
有一个有效的主机名时,
host
和
port
被解析,但当不合法时,
authority
被视为自由格式文本,不再进一步解析。
更新
来自评论:
System.out.println( new URI(null, null, "/5-12-145-35_s-81", 443, null, null, null))
输出: ///5-12-145-35_s-81:443。我正在将其作为主机名。
您调用的URI
构造函数是一个方便方法,它只需构建一个完整的URI字符串,然后对其进行解析。
传递"5-12-145-35_s-81", 443
变成//5-12-145-35_s-81:443
。
传递"/5-12-145-35_s-81", 443
变成///5-12-145-35_s-81:443
。
在第一个示例中,它是一个host和port,无法解析。
在第二个示例中,authority部分为空,/5-12-145-35_s-81:443
是一个path。
URI uri1 = new URI(null, null, "/5-12-145-35_s-81", 443, null, null, null);
System.out.println("uri = " + uri1);
System.out.println(" authority = " + uri1.getAuthority());
System.out.println(" host = " + uri1.getHost());
System.out.println(" port = " + uri1.getPort());
System.out.println(" path = " + uri1.getPath());
输出
uri = ///5-12-145-35_s-81:443
authority = null
host = null
port = -1
path = /5-12-145-35_s-81:443