>创建一个在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();
// ...