我过去使用过协议处理程序来覆盖默认的 http 处理程序并创建我自己的自定义处理程序,我认为这种方法仍然适用于 Android。我正在尝试覆盖我的 Android 应用程序请求的任何 http 或 https URL,并在某些情况下将其传递给自定义处理程序。但是我仍然想在其他情况下访问网络资源。如何检索默认的 http/https 协议处理程序?在将我的覆盖放置到位之前,我正在尝试类似以下内容来加载默认处理程序:
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;
}
}
我的覆盖逻辑工作如下:
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;
}
});
覆盖有效,但在我想要正常的 URL 连接行为的情况下,我无法加载默认值。尝试清除我的 StreamHandlerFactory 如下:
URL.setURLStreamHandlerFactory(null);
引发错误:
java.lang.Error: Factory already set
at java.net.URL.setURLStreamHandlerFactory(URL.java:112)