5

我正在编写一个半包装 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 类的文档?谁能解释我所看到的?

4

1 回答 1

6

这里有一些基于您的片段的可执行代码:

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.print,然后使用System.out.println在同一行中打印路径和文件的结果。

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=val1
于 2015-05-13T07:56:28.917 回答