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: 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;
}
}