I write a small java tool and a at the beginning I have to parse a url. I would like to know, what you are thinking about my solution and if there is a better way?
Here are some examples:
aaa://username:password@server:port/dir/
aaa://server:port/dir/
aaa://server:port
Every kind of String is possible, if the user is not carefully. So it is possible, that my function get such a string
aaa://username:pass
too. But the string always starts witch aaa://.
Here is my code:
url = url.replaceFirst("aaa://", "");
String params[] = url.split("@");
if(params[0].compareTo("") != 0) {
String paramsfst[] = params[0].split(":");
if(params.length == 1) {
if(paramsfst.length >= 1) {
this.server = parsePort(paramsfst[0]);
if(paramsfst.length == 2) {
this.port = parsePort(paramsfst[1]);
}
}
} else {
String paramssec[] = params[1].split(":");
if(paramssec.length >= 1) {
this.server = parsePort(paramssec[0]);
if(paramssec.length == 2) {
this.port = parsePort(paramssec[1]);
}
}
if(paramsfst.length == 2) {
this.username = paramsfst[0];
this.password = paramsfst[1];
}
}
if(url.contains("/")) {
this.path = url.substring(url.indexOf("/"), url.length() -1);
}
private String parsePort(String port) {
int i = port.indexOf("/");
if(i == -1) {
return port;
}
return port.substring(0, i);
}
What do you think?
Have you looked at the URL class?
See here for an example.