gpt4 book ai didi

java - 检查 URL 相等性的正确方法

转载 作者:IT老高 更新时间:2023-10-28 20:59:50 36 4
gpt4 key购买 nike

我有以下场景:

URL u1 = new URL("http://www.yahoo.com/");
URL u2 = new URL("http://www.yahoo.com");

if (u1.equals(u2)) {
System.out.println("yes");
}
if (u1.toURI().equals(u2.toURI())) {
System.out.println("uri equality");
}
if (u1.toExternalForm().equals(u2.toExternalForm())) {
System.out.println("external form equality");
}
if (u1.toURI().normalize().equals(u2.toURI().normalize())) {
System.out.println("uri normalized equality");
}

这些检查都没有成功。只有路径不同:u1 的路径为“/”,而 u2 的路径为“”。这些 URL 是否指向相同的资源,有没有办法让我在不打开连接的情况下检查这样的事情?我是否误解了有关 URL 的一些基本内容?

编辑 我应该声明需要非 hacky 检查。说空路径 ==/是否合理?我希望没有这种代码

最佳答案

从 2007 年的 JavaOne 开始:

The second puzzle, aptly titled "More Joys of Sets" has the user create HashMap keys that consist or several URL objects. Again, most of the audience was unable to guess the correct answer.

The important thing the audience learned here is that the URL object's equals() method is, in effect, broken. In this case, two URL objects are equal if they resolve to the same IP address and port, not just if they have equal strings. However, Bloch and Pugh point out an even more severe Achilles' Heel: the equality behavior differs depending on if you're connected to the network, where virtual addresses can resolve to the same host, or if you're not on the net, where the resolve is a blocking operation. So, as far as lessons learned, they recommend:

Don't use URL; use URI instead. URI makes no attempt to compare addresses or ports. In addition, don't use URL as a Set element or a Map key.
For API designers, the equals() method should not depend on the environment. For example, in this case, equality should not change if a computer is connected to the Internet versus standalone.


来自 URI 等于文档:

For two hierarchical URIs to be considered equal, their paths must be equal and their queries must either both be undefined or else be equal.

在您的情况下,这两条路径是不同的。一个是“/”,另一个是“”。


根据 URI RFC §6.2.3:

Implementations may use scheme-specific rules, at further processing cost, to reduce the probability of false negatives. For example, because the "http" scheme makes use of an authority component, has a default port of "80", and defines an empty path to be equivalent to "/", the following four URIs are equivalent:

 http://example.com
http://example.com/
http://example.com:/
http://example.com:80/

这个实现似乎没有使用特定于方案的规则。


资源:

关于java - 检查 URL 相等性的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3771081/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com