Java Reference
In-Depth Information
String url = base + params.collect { k,v -> "$k=$v" }.join('&')
Finally, I take advantage of the Groovy JDK. In the Groovy JDK the
String
class
contains a method called
toURL
, which converts the
String
into an instance of
java.net.URL
. The
URL
class in the Groovy JDK includes a
getText
method, which
I can invoke as a
text
property.
Property access
In Groovy, the standard idiom is to access a property, which is automatically converted to
a getter or setter method.
The code to retrieve the desired CSV string is
url.toURL().text
Now I can use the
split
method on String, which divides the string at the commas and
returns a list containing the elements. I can then take advantage of Groovy's cool multival-
ued return capability to assign each value to an output variable.
The complete script is shown next and displayed graphically in
figure 3.3
:
String address = [street,city,state].collect {
URLEncoder.encode(it,'UTF-8')
}.join(',+')
def params = [q:address,sensor:false,output:'csv',key:'ABQIAAAAaUT...']
String base = 'http://maps.google.com/maps/geo?'
String url = base + params.collect { k,v -> "$k=$v" }.join('&')
(code,level,lat,lng) = url.toURL().text.split(',')