In this example we will show ways to assemble a URI with groovy's URIBuilder. In a comparable example we demonstrate how to build a uri from a string in java, springframework and apache commons.
General operations
The general operations code snippet shows how to get the host, scheme, path, and port which are all common operations.
@Test
void general_operations() {
def uri = new URIBuilder( 'http://www.leveluplunch.com:80/examples/' )
assert "www.leveluplunch.com" == uri.host
assert "/examples/" == uri.path
assert "http" == uri.scheme
assert 80 == uri.port
assert "oath"
}
Get fragment
The fragment identifier is optional part at the end of a URI introduced with a hash mark #
and can be retreived with uri.gragment
.
@Test
void working_with_fragments() {
def uri = new URIBuilder( 'http://www.leveluplunch.com/#fragment' )
assert "fragment" == uri.fragment
}
Working with query parameters
The working with query parameters snippet shows how to get, remove, replace and add multiple query parameters.
@Test
void working_with_query_parameters() {
def uri = new URIBuilder( 'http://www.leveluplunch.com?a=10&b=15' )
//get
assert uri.query.a == '10'
assert uri.query.b == '15'
//remove parameters
uri.removeQueryParam 'a'
assert "http://www.leveluplunch.com?b=15" == uri.toString()
//add parameters
uri.addQueryParam "foo", "bar"
assert "http://www.leveluplunch.com?b=15&foo=bar" == uri.toString()
//add multiple query parameters
uri.addQueryParams([n:10, c:33])
assert "http://www.leveluplunch.com?b=15&foo=bar&n=10&c=33" == uri.toString()
//replace existing query parameters
uri.query = [java:"examples", groovy:"examples", exercises:"java"]
assert "http://www.leveluplunch.com?java=examples&groovy=examples&exercises=java" == uri.toString()
}