4

我想对具有不受支持的 url 协议(方案)的字符串进行 url 编码。因此,在第 3 行,将引发异常。无论如何让 URL 类支持“mmsh”或任何其他“custom_name”方案?

编辑:我不想为我的应用程序注册一些协议。我只想能够在没有“不支持的协议”异常的情况下使用 URL 类。我使用 URL 类只是为了解析和整理 url 字符串。

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()); 
4

1 回答 1

2

我根据提供的代码创建了示例程序 URL to load resources from the classpath in JavaCustom URL protocols and multiple classloaders它似乎工作正常。

@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);
        }
    }
}
于 2012-10-30T08:12:17.810 回答