Use this library to safely create valid, correctly encoded URL strings with a fluent API.
Use the jcenter()
repository and add:
compile 'com.mmdemirbas:url-builder:1.0.0'
To configure JCenter repo, go here and click "Set me up", then add:
<dependency>
<groupId>com.mmdemirbas</groupId>
<artifactId>url-builder</artifactId>
<version>1.0.0</version>
</dependency>
import com.mmdemirbas.urlbuilder.UrlBuilder;
import static com.mmdemirbas.urlbuilder.UrlBuilder.pair;
// showcase the different encoding rules used on different URL components
UrlBuilder.from("http", "foo.com")
.addPath("with spaces")
.addPaths("path", "with", "varArgs")
.addPath("&=?/", pair("matrix", "param?"))
.setQuery(pair("fancy + name", "fancy?=value"))
.setFragment("#?=")
.toUrlString());
UrlBuilder.from("http://foo.com/with%20spaces/path/with/varArgs/&=%3F%2F;matrix=param%3F?fancy%20%2B%20name=fancy?%3Dvalue#%23?=")
.toUrlString());
UrlBuilder.from(new URL("http://foo.com/with%20spaces/path/with/varArgs/&=%3F%2F;matrix=param%3F?fancy%20%2B%20name=fancy?%3Dvalue#%23?="))
.toUrlString());
// all above examples produce:
// http://foo.com/with%20spaces/path/with/varArgs/&=%3F%2F;matrix=param%3F?fancy%20%2B%20name=fancy?%3Dvalue#%23?=
See this blog post for a through explanation.
Ideally, the Java SDK would provide a good way to build properly encoded URLs. Unfortunately, it does not.
URLEncoder
seems like a thing that you want to use, but amazingly enough it actually does HTML form encoding, not URL encoding.
URL encoding is also not something that can be done once you've formed a complete URL string. If your URL is already correctly encoded, you do not need to do anything. If it is not, it is impossible to parse it into its constituent parts for subsequent encoding. You must construct a url piece by piece, correctly encoding each piece as you go, to end up with a valid URL string. The encoding rules are also different for different parts of the URL (path, query param, etc.)
Since the URLs that we use in practice for HTTP have somewhat different rules than "generic" URLs, UrlBuilder errs on the side of usefulness for HTTP-specific URLs. Notably, this means that '+' is percent-encoded to avoid being interpreted as a space. Also, in the URL/URI specs, the query string's format is not defined, but in practice it is used to hold key=value
pairs separated by &
.
Run ./gradlew build
.
URL handling behaviour of Spring MVC tested with SpringTest.kt and results summarized here.