at java.net.url init,注册并使用自定义java.net.URL协议

>创建一个在connect()方法中执行作业的自定义

URLConnection实现。

public class CustomURLConnection extends URLConnection {

protected CustomURLConnection(URL url) {

super(url);

}

@Override

public void connect() throws IOException {

// Do your job here. As of now it merely prints "Connected!".

System.out.println("Connected!");

}

}

不要忘记覆盖并实现像getInputStream()这样的其他方法。由于此信息在该问题中缺少,所以不能给出更多细节。

>创建一个自定义的URLStreamHandler实现,它在openConnection()中返回它。

public class CustomURLStreamHandler extends URLStreamHandler {

@Override

protected URLConnection openConnection(URL url) throws IOException {

return new CustomURLConnection(url);

}

}

如果需要,不要忘记覆盖和实施其他方法。

public class CustomURLStreamHandlerFactory implements URLStreamHandlerFactory {

@Override

public URLStreamHandler createURLStreamHandler(String protocol) {

if ("customuri".equals(protocol)) {

return new CustomURLStreamHandler();

}

return null;

}

}

请注意协议是always小写。

URL.setURLStreamHandlerFactory(new CustomURLStreamHandlerFactory());

请注意,Javadoc明确表示您最多可以设置一次。因此,如果您打算在同一应用程序中支持多种自定义协议,则需要生成自定义的URLStreamHandlerFactory实现,以覆盖所有createURLStreamHandler()方法。

或者,如果您不喜欢德米特法则,请将其全部放在匿名类中进行代码缩小:

URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {

public URLStreamHandler createURLStreamHandler(String protocol) {

return "customuri".equals(protocol) ? new URLStreamHandler() {

protected URLConnection openConnection(URL url) throws IOException {

return new URLConnection(url) {

public void connect() throws IOException {

System.out.println("Connected!");

}

};

}

} : null;

}

});

如果您已经使用Java 8,请用lambda替换URLStreamHandlerFactory功能界面以进一步分类:

URL.setURLStreamHandlerFactory(protocol -> "customuri".equals(protocol) ? new URLStreamHandler() {

protected URLConnection openConnection(URL url) throws IOException {

return new URLConnection(url) {

public void connect() throws IOException {

System.out.println("Connected!");

}

};

}

} : null);

现在你可以使用它如下:

URLConnection connection = new URL("CustomURI:blabla").openConnection();

connection.connect();

// ...

或者根据规范使用较低的协议:

URLConnection connection = new URL("customuri:blabla").openConnection();

connection.connect();

// ...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值