我正在编写一个半包装 Java 的实用程序类URL class
,并且我编写了一堆测试用例来验证我用自定义实现包装的方法。我不理解某些 Java 的某些URL
字符串的 getter 的输出。
根据 RFC 3986 规范,路径组件定义如下:
The path is terminated by the first question mark ("?") or number sign
("#") character, or by the end of the URI.
查询组件定义如下:
The query component is indicated by the first question
mark ("?") character and terminated by a number sign ("#") character
or by the end of the URI.
我有几个测试用例被 Java 视为有效的 URL,但是路径、文件和查询的 getter 不会返回我预期的值:
URL url = new URL("https://www.somesite.com/?param1=val1");
System.out.print(url.getPath());
System.out.println(url.getFile());
System.out.println(url.getQuery());
上面的结果如下:
//?param1=val1
param1=val1
<empty string>
我的另一个测试用例:
URL url = new URL("https://www.somesite.com?param1=val1");
System.out.print(url.getPath());
System.out.println(url.getFile());
System.out.println(url.getQuery());
上面的结果如下:
?param1=val1
param1=val1
<empty string>
根据 Java 的文档URL
:
public String getFile()
Gets the file name of this URL. The returned file portion will be the
same as getPath(), plus the concatenation of the value of getQuery(), if
any. If there is no query portion, this method and getPath() will return
identical results.
Returns:
the file name of this URL, or an empty string if one does not exist
所以,我的测试用例在getQuery()
被调用时会产生空字符串。在这种情况下,我希望getFile()
返回与getPath()
. 不是这种情况。
我曾期望两个测试用例的输出如下:
<empty string>
?param1=val1
param1=val1
也许我对 RFC 3986 的解释是不正确的。但是我看到的输出也不符合 URL 类的文档?谁能解释我所看到的?