4

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()); 
3
  • 1
    In java you need to extend from URLStreamHandler check example here Commented Oct 30, 2012 at 7:38
  • 1
    This might be of some help try : stackoverflow.com/questions/11421048/… Commented Oct 30, 2012 at 7:47
  • Thank you all, but 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. Commented Oct 30, 2012 at 8:03

1 Answer 1

2

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.