关于自定义URLStreamHandler的一次踩坑
- 20180625 lambo init
说明
一般自定义实现url的协议解析.方案为实现URLStreamHandler.实现其 openConnection 就可以了, 如果我们执行 new URL("xx://aa/ff").hashCode();
public synchronized int hashCode() {
if (hashCode != -1)
return hashCode;
// 实现为转发给自实现的URLStreamHandler 进行处理
hashCode = handler.hashCode(this);
return hashCode;
}
默认URLStreamHandler 处理hashCode为
protected int hashCode(URL u) {
int h = 0;
// Generate the protocol part.
String protocol = u.getProtocol();
if (protocol != null)
h += protocol.hashCode();
// Generate the host part.
InetAddress addr = getHostAddress(u);
if (addr != null) {
h += addr.hashCode();
} else {
String host = u.getHost();
if (host != null)
h += host.toLowerCase().hashCode();
}
// Generate the file part.
String file = u.getFile();
if (file != null)
h += file.hashCode();
// Generate the port part.
if (u.getPort() == -1)
h += getDefaultPort();
else
h += u.getPort();
// Generate the ref part.
String ref = u.getRef();
if (ref != null)
h += ref.hashCode();
return h;
}
其会进行一次url的访问拿到内容参数 hashCode. 但一般我们定义一个url是内容不会变化的. 我们自定义协议可以使用 以下代码
@Override
protected int hashCode(URL u) {
if(null == u) {
return 0;
}
return u.toString().hashCode();
}