关于自定义URLStreamHandler的一次踩坑

关于自定义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();
    }

转载于:https://my.oschina.net/u/727875/blog/1835171

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值