2012-10-30 29 views
5

我想url編碼一個不支持url協議(scheme)的字符串。 因此,在第三行,將會拋出異常。反正有URL類支持「mmsh」或任何其他「custom_name」方案嗎?如何擴展URL類以支持java(android)中的其他協議?

編輯:我不想爲我的應用程序註冊一些協議。我只想在沒有「不受支持的協議」異常的情況下使用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()); 
+1

在java中,你需要延長從[URLStreamHandler的(http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLStreamHandler.html)檢查例子[這裏] (http://stackoverflow.com/questions/861500/url-to-load-resources-from-the-classpath-in-java) –

+1

這可能是一些幫助嘗試:http://stackoverflow.com/questions/ 11421048/android-ios-custom-uri-protocol-handling –

+0

謝謝大家,但我不想爲我的應用程序註冊一些協議。我只想在沒有「不受支持的協議」異常的情況下使用URL類。我正在使用URL類來解析和整理url字符串。 – frankish

回答

3

我創建的樣本程序基礎上提供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); 
     } 
    } 
}