Protocol Handlers

When we call the URL.openConnection() method, the java.net package uses the
  • default URLStreamHandlerFactory to get a
  • default URLStreamHandler to open a
  • default URLConnection.
We can install our own stream handler factory to get first crack at any URL.

If we want to handle the specified protocol,

  • we return our own URLStreamHandler
  • otherwise we return null
and java.net will use the default factory.

public class HelpBrowser {
    ...
    URL.setURLStreamHandlerFactory(new KahunaURLStreamHandlerFactory());
    ...
}

class KahunaURLStreamHandlerFactory implements URLStreamHandlerFactory {
    public URLStreamHandler createURLStreamHandler(String protocol) {
        if (protocol.equalsIgnoreCase("kahuna")) {
            return new KahunaURLStreamHandler();
        } else {
            return null;
        }
    }
}

class KahunaURLStreamHandler extends URLStreamHandler {
    protected URLConnection openConnection(URL url) throws IOException {
        return new KahunaURLConnection(url);
    }
}

class KahunaURLConnection extends URLConnection {
    public InputStream getInputStream() throws IOException {
        String page = KahunaServer.getPage(url);
        return new ByteArrayInputStream(page.getBytes());
    }

    public void connect() throws IOException {}
    public String getContentType() { return "text/html"; }
}