-
Create a custom
URLConnection
implementation which performs the job inconnect()
method.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!"); } }
Don’t forget to override and implement other methods like
getInputStream()
accordingly. More detail on that cannot be given as this information is missing in the question.
-
Create a custom
URLStreamHandler
implementation which returns it inopenConnection()
.public class CustomURLStreamHandler extends URLStreamHandler { @Override protected URLConnection openConnection(URL url) throws IOException { return new CustomURLConnection(url); } }
Don’t forget to override and implement other methods if necessary.
-
Create a custom
URLStreamHandlerFactory
which creates and returns it based on the protocol.public class CustomURLStreamHandlerFactory implements URLStreamHandlerFactory { @Override public URLStreamHandler createURLStreamHandler(String protocol) { if ("customuri".equals(protocol)) { return new CustomURLStreamHandler(); } return null; } }
Note that protocols are always lowercase.
-
Finally register it during application’s startup via
URL#setURLStreamHandlerFactory()
URL.setURLStreamHandlerFactory(new CustomURLStreamHandlerFactory());
Note that the Javadoc explicitly says that you can set it at most once. So if you intend to support multiple custom protocols in the same application, you’d need to generify the custom
URLStreamHandlerFactory
implementation to cover them all inside thecreateURLStreamHandler()
method.
Alternatively, if you dislike the Law of Demeter, throw it all together in anonymous classes for code minification:
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; } });
If you’re on Java 8 already, replace the
URLStreamHandlerFactory
functional interface by a lambda for further minification: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);
Now you can use it as follows:
URLConnection connection = new URL("CustomURI:blabla").openConnection();
connection.connect();
// ...
Or with lowercased protocol as per the spec:
URLConnection connection = new URL("customuri:blabla").openConnection();
connection.connect();
// ...