At the heart of any HTTP request, there is a Universal Resource Locator (URL) or a more generic Universal Resource Identifier (URI) which identifies the target of the operation we need to perform.
We have seen in the previous recipes (for example, the Downloading content from the Internet recipe) that it's very hard to avoid dealing with URLs when interacting with the HTTP protocol. In this recipe, we are going to present a more structured approach to constructing and modifying complex URLs with the help of an additional Groovy library.
If you have worked with Java's URL
class before, you know that the only way to construct instances of that class is to provide a full URL to the constructor, which will return an immutable (non-changeable) object.
Groovy's core does not add any special support for URL manipulation apart from what Java already offers, but there is an officially supported HttpBuilder
module that is hosted on Groovy's website (http://groovy.codehaus.org/modules/http-builder) and that can be used to make more accessible URL creation and modification:
@Grab
that module and import the URIBuilder
class, which will help us with our task:@Grab( group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6' ) import groovyx.net.http.URIBuilder
URIBuilder
instance and pass baseUri
to that:def baseUri = 'http://groovy.services.com/service1/operation2' def uri = new URIBuilder(baseUri)
uri.with { scheme = 'https' host = 'localhost' port = 8080 fragment = 'some_anchor' path = 'some_folder/some_page.html' query = [param1: 2, param2: 'x'] }
URIBuilder
, we can create URI
, URL
, or String
instances at any point:uri.toURI() uri.toURL() uri.toString()
Internally the URIBuilder
class stores all URI components such as, scheme (http://
and https://
), user information (username:password
), host, port, path, and fragment separately. This allows creating new URLs incrementally and changing existing URLs without a need to write custom string parsing/concatenating logic.
Other implementations of URI builder functionality can be found in JAX-WS API and Apache's HttpClient available in the following link: