I've used protocol handlers in the past overriding the default http handler and creating my own custom handlers and I was thinking the approach still works on Android. I am trying to override any http or https URL requested by my Android app and pass it to a custom handler under certain situations. However I still would like to access web resources in other cases. How do I retrieve the default http/https protocol handlers? I'm trying something like the following to load the default handler before putting my override in place:
static URLStreamHandler handler;
static {
Class<?> handlerClass;
try {
handlerClass = Class.forName("net.www.protocol.http.Handler");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Error loading clas for default http handler.", e);
}
Object handlerInstance;
try {
handlerInstance = handlerClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Error instantiating default http handler.", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Error accessing default http handler.", e);
}
if (! (handlerInstance instanceof URLStreamHandler)) {
throw new RuntimeException("Wrong class type, " + handlerInstance.getClass().getName());
} else {
handler = (URLStreamHandler) handlerInstance;
}
}
My override logic works as follows:
URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
public URLStreamHandler createURLStreamHandler(String protocol) {
URLStreamHandler urlStreamHandler = new URLStreamHandler() {
protected URLConnection openConnection(URL url) throws IOException {
return new URLConnection(url) {
public void connect() throws IOException {
Log.i(getClass().getName(), "Global URL override!!! URL load requested " + url);
}
};
}
};
return shouldHandleURL(url) ? urlStreamHandler : handler;
}
});
The override works but I cannot load the default in cases where I want normal URL connection behavior. Trying to clear my StreamHandlerFactory as follows:
URL.setURLStreamHandlerFactory(null);
Throws an error:
java.lang.Error: Factory already set
at java.net.URL.setURLStreamHandlerFactory(URL.java:112)