Java Reference
In-Depth Information
def base = 'http://maps.googleapis.com/maps/api/geocode/xml?'
To assemble the query string, consider a list containing the stadium name, city, and state:
[stadium.name, stadium.city, stadium.state]
Each of these values could potentially include spaces, apostrophes, or other symbols that
wouldn't be legal in a URL. I therefore need to URL-encode each of the values. As I
showed in the last section, applying the collect method to a list returns a new list con-
taining the transformed values. In this case, the transformation I want is to use the encode
method in the java.net.URLEncoder , as shown:
[stadium.name, stadium.city, stadium.state]. collect {
URLEncoder.encode(it,'UTF-8')
}.join(',')
If you use a closure without specifying a dummy parameter, as here, each element of the
list is assigned to a variable called it. The body of the closure executes the static en-
code method on the name, city, and state, using the UTF-8 encoding scheme. The result
is a list containing the encoded values. Finally, the values of the list are joined into a string
using “ , ” as a separator.
That takes care of assembling the address. Forming a complete query string is done using
the same closure used in the Google Chart listing. The complete process so far is shown
here:
def url = base + [sensor:false,
address: [stadium.name, stadium.city, stadium.state]. collect {
URLEncoder.encode(it,'UTF-8')
}. join (',')
]. collect {k,v -> "$k=$v"}. join ('&')
Building a query string
The combination of parameter map, collect closure, and join method is a convenient
way to build a query string. A developer can store the parameters in any order, or accept
them from the user (as in a Grails application), and turn them into a query string with a
minimum of effort.
Search WWH ::




Custom Search