I need generate valid URLs.
Example: I pass the url: google.com . The generator returns http://google.com/ .
Some browsers do this. I tried do my own algorithm, but has fails.
Another example: http://www.yadayadayada.com/../test returns http://www.yadayadayada.com/test/
public String generateValidURL(String url) {
int pos = 0;
try {
url = url.trim();
url = url.replaceAll(" ", "%20");
if (url.startsWith("http") && (!url.substring(4).startsWith("://"))) {
for (int i = 4; i < 7; i++) {
if ((url.charAt(i) == '/') || (url.charAt(i) == ':')) {
pos = i;
}
}
url = url.substring(pos + 1);
}
if(url.startsWith("https")){
url = url.replace("https", "http");
}
if (!url.startsWith("http")) {
url = "http://" + url;
}
if (!url.substring(7).contains("/")) {
url += "/";
}
url = url.replace(",", ".");
url = url.replace("../", "/");
url = url.substring(0, 7) + url.substring(7).replace("//", "/");
return url;
} catch (Exception e) {
System.out.println("Error generating valid URL : " + e);
return null;
}
}
Update: now that is is clearer what you want to achieve – I don’t think there’s an utility for that. Your method should do, just debug it.
Original answer:
In fact, you may want to use the
URIclass instead:You can use
uri.resolve("../relativePath")and it will get resolved. But have in mind that your example with/../test==/testis not proper (you’d have to handle this case manually)