Getting a reference to Java's default http(s) URLStreamHandler

后端 未结 3 1363
粉色の甜心
粉色の甜心 2020-12-17 01:37

I have a library that I need to use in one of my projects, which unfortunately registers its own URLStreamHandler to handle http-URLs. Is there a w

3条回答
  •  情歌与酒
    2020-12-17 02:25

    Here's Markus A solution rewritten for Android:

    public static URLStreamHandler getURLStreamHandler(String protocolIdentifier) {
        try {
            URL url = new URL(protocolIdentifier);
            Field handlerField = URL.class.getDeclaredField("handler");
            handlerField.setAccessible(true);
            return (URLStreamHandler)handlerField.get(url);
         } catch (Exception e) {
            return null;
        }
    }
    

    The method getURLStreamHandler doesn't exist in android, so it needs to be done differently. The protocolIdentifier is the protocol name plus the colon. You need to pass in a value so that can be used to instantiate a URL instance for the protocol URLStreamHandler you want. If you want the standard "jar:" protocol handler you must enter something like this: "jar:file:!/". The "file" could be replaced with "http" or "https", as they all get you the same handler instance.

    The standard Handlers that android supports are http, https, file, jar, ftp.

提交回复
热议问题