我正在编写一个半包装Java的URL class的实用程序类,并且我已经编写了一系列测试用例来验证我用自定义实现包装的方法。我不理解某些URL字符串的一些Java的输出。
根据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也许我对RFC3986的解释是不正确的。但我看到的输出也与URL类的文档不一致?谁能解释一下我看到的是什么?
发布于 2015-05-13 15:56:29
下面是基于您的代码片段的一些可执行代码:
import java.net.MalformedURLException;
import java.net.URL;
public class URLExample {
public static void main(String[] args) throws MalformedURLException {
printURLInformation(new URL("https://www.somesite.com/?param1=val1"));
printURLInformation(new URL("https://www.somesite.com?param1=val1"));
}
private static void printURLInformation(URL url) {
System.out.println(url);
System.out.println("Path:\t" + url.getPath());
System.out.println("File:\t" + url.getFile());
System.out.println("Query:\t" + url.getQuery() + "\n");
}
}运行得很好,这就是你所期望的结果。惟一的区别是,您使用了一个后跟System.out.println的System.out.print,,它在同一行中打印路径和文件的结果。
https://www.somesite.com/?param1=val1
Path: /
File: /?param1=val1
Query: param1=val1
https://www.somesite.com?param1=val1
Path:
File: ?param1=val1
Query: param1=val1https://stackoverflow.com/questions/30003540
复制相似问题