frankish
frankish

Reputation: 6846

How to extend URL class to support other protocols in java (android)?

I want to url encode a string that has an unsupported url protocol(scheme). So, on the 3rd line, an exception will be thrown. Is there anyway to make URL class support "mmsh" or any other "custom_name" scheme?

EDIT: I do not want to register some protocols for my application. I just want to be able to use URL class without "unsupported protocol" exception. I am using URL class just to parse and tidy the url string.

String string="mmsh://myserver.com/abc";

String decodedURL = URLDecoder.decode(string, "UTF-8");
URL url = new URL(decodedURL);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); 

Upvotes: 4

Views: 4528

Answers (1)

Amit Deshpande
Amit Deshpande

Reputation: 19185

I created sample program based on the code provided on URL to load resources from the classpath in Java and Custom URL protocols and multiple classloaders and it seems to work fine.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    URL url;
    try {

        url = new URL(null, "user:text.xml", new Handler());
        InputStream ins = url.openStream();
        ins.read();
        Log.d("CustomURL", "Created and accessed it using custom handler ");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
public static class Handler extends URLStreamHandler {
    @Override
    protected URLConnection openConnection(URL url) throws IOException {
        return new UserURLConnection(url);
    }

    public Handler() {
    }

    private static class UserURLConnection extends URLConnection {
        private String fileName;
        public UserURLConnection(URL url) {
            super(url);
            fileName = url.getPath();
        }
        @Override
        public void connect() throws IOException {
        }
        @Override
        public InputStream getInputStream() throws IOException {

            File absolutePath = new File("/data/local/", fileName);
            return new FileInputStream(absolutePath);
        }
    }
}

Upvotes: 2

Related Questions