如何扩展URL类以支持java(android)中的其他协议?
我想对具有不受支持的url协议(方案)的字符串进行url编码。 因此,在第3行,将抛出一个异常。是否有任何方法使URL类支持“mmsh”或任何其他“自定义名称”方案 编辑:我不想为我的应用程序注册一些协议。我只想能够使用URL类而不出现“不受支持的协议”异常。我使用URL类只是解析和整理URL字符串如何扩展URL类以支持java(android)中的其他协议?,java,android,url,url-encoding,Java,Android,Url,Url Encoding,我想对具有不受支持的url协议(方案)的字符串进行url编码。 因此,在第3行,将抛出一个异常。是否有任何方法使URL类支持“mmsh”或任何其他“自定义名称”方案 编辑:我不想为我的应用程序注册一些协议。我只想能够使用URL类而不出现“不受支持的协议”异常。我使用URL类只是解析和整理URL字符串 String string="mmsh://myserver.com/abc"; String decodedURL = URLDecoder.decode(string, "UTF-8"); U
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());
我根据和上提供的代码创建了示例程序,它似乎运行良好
@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);
}
}
}
在java中,您需要从检查示例进行扩展,这可能会有所帮助。请尝试:谢谢大家,但我不想为我的应用程序注册一些协议。我只想能够使用URL类而不出现“不受支持的协议”异常。我使用URL类只是解析和整理URL字符串。