首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java URL类getPath()、getQuery()和getFile()与RFC3986 URI语法不一致

Java URL类getPath()、getQuery()和getFile()与RFC3986 URI语法不一致
EN

Stack Overflow用户
提问于 2015-05-02 22:38:37
回答 1查看 9.3K关注 0票数 5

我正在编写一个半包装Java的URL class的实用程序类,并且我已经编写了一系列测试用例来验证我用自定义实现包装的方法。我不理解某些URL字符串的一些Java的输出。

根据RFC 3986规范,路径组件定义如下:

代码语言:javascript
复制
The path is terminated by the first question mark ("?") or number sign   
("#") character, or by the end of the URI.

查询组件的定义如下:

代码语言:javascript
复制
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没有返回我所期望的值:

代码语言:javascript
复制
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());

以上结果将产生以下输出:

代码语言:javascript
复制
//?param1=val1
param1=val1
<empty string>

我的另一个测试用例:

代码语言:javascript
复制
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());

以上结果将产生以下输出:

代码语言:javascript
复制
?param1=val1
param1=val1
<empty string>

根据Java URL的文档

代码语言:javascript
复制
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()相同的值。事实并非如此。

对于这两个测试用例,我都期望得到以下输出:

代码语言:javascript
复制
<empty string>
?param1=val1
param1=val1

也许我对RFC3986的解释是不正确的。但我看到的输出也与URL类的文档不一致?谁能解释一下我看到的是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-13 15:56:29

下面是基于您的代码片段的一些可执行代码:

代码语言:javascript
复制
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.printlnSystem.out.print,,它在同一行中打印路径和文件的结果。

代码语言:javascript
复制
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
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30003540

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档