1
A method takes snippets from a URL and needs to concatenate them coherently, but without presupposing details about each one.
Examples:
http://server + /path + /resource.js => http://server/path/resource.js
http://server/ + /path/ + /resource.js => http://server/path/resource.js
http://server + path + resource.js => http://server/path/resource.js
//server + path + resource.js => //server/path/resource.js
Basically, coherence is in leaving only one bar /
between each element and not change the structure of the URL as a whole, as in the last example where the protocols remains missing.
My first approach was simply to create a routine that brings together two parts by checking the bars:
String joinUrlSafely(final String s1, final String s2) {
final boolean s1HasSlash = s1.endsWith("/");
final boolean s2HasSlash = s2.startsWith("/");
if (s1HasSlash && s2HasSlash) {
return s1 + s2.substring(1); //os dois tem barra, remove uma
} else if (!s1HasSlash && !s2HasSlash) {
return s1 + "/" + s2; //nenhum tem barra, coloca uma
} else {
return s1 + d2; //um dos dois tem barra, deixa ela lá
}
}
However, I was not satisfied and the question remains:
Is there an API in Java or in some commonly used library (Apache, Guava, ...) that does this in a more secure and standardized way? Some kind of
UrlBuilder
?
I do not know if there is such a thing, because as your code shows, it is a trivial task. By the way, I would do something very similar to what you’re doing.
– Victor Stafusa