Working with URIs that contain query parameters implies encoding these parameters. The Java built-in method for accomplishing this task is URLEncoder.encode(). But concatenating and encoding several query parameters leads to something similar to the following:
URI uri = URI.create("http://localhost:8080/books?name=" +
URLEncoder.encode("Games & Fun!", StandardCharsets.UTF_8) +
"&no=" + URLEncoder.encode("124#442#000", StandardCharsets.UTF_8) +
"&price=" + URLEncoder.encode("$23.99", StandardCharsets.UTF_8)
);
When we have to work with a significant number of query parameters, this solution is not very convenient. We can, however, try to write a helper method to hide the URLEncoder.encode() method in a loop over a collection of query parameters, or we can rely on a URI builder.
In Spring, the URI builder is org.springframework.web.util.UriComponentsBuilder. The following code is self-explanatory:
URI uri = UriComponentsBuilder.newInstance()
.scheme("http")
.host("localhost")
.port(8080)
.path("books")
.queryParam("name", "Games & Fun!")
.queryParam("no", "124#442#000")
.queryParam("price", "$23.99")
.build()
.toUri();
In a non-Spring application, we can rely on a URI builder such as the urlbuilder library (https://github.com/mikaelhg/urlbuilder). The code that's bundled with this book contains an example of using this.