【问题标题】:How to extend URL class to support other protocols in java (android)?如何扩展 URL 类以支持 java (android) 中的其他协议?
【发布时间】:2012-10-30 07:30:26
【问题描述】:

我想对具有不受支持的 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()); 

【问题讨论】:

  • 在java中你需要从URLStreamHandler扩展检查示例here
  • 这可能会有所帮助尝试:stackoverflow.com/questions/11421048/…
  • 谢谢大家,但我不想为我的应用程序注册一些协议。我只想能够在没有“不支持的协议”异常的情况下使用 URL 类。我使用 URL 类只是为了解析和整理 url 字符串。

标签: java android url url-encoding


【解决方案1】:

我根据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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 2023-03-04
    • 1970-01-01
    • 2014-12-30
    • 2013-05-19
    • 1970-01-01
    相关资源
    最近更新 更多