Skip to content
Tim Yates edited this page Apr 9, 2015 · 1 revision

HTTPURLClient is an alternate implementation that does not rely on HttpClient sockets for communication. The main motivation behind this is use in Google App Engine. GAE does not allow direct socket communication; instead web resources are accessed only via the HttpURLConnection class. Since HttpURLConnection is somewhat cumbersome to use (particularly for REST operations,) HttpURLClient applies some of HTTPBuilder's idioms on top of an HttpURLConnection.

HttpURLClient supports automatic content-type parsing and request marshalling, URI manipulation and the convenient header access.

Here is an example of reading London weather using both JSON and XML:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7')
 
import groovyx.net.http.HttpURLClient
 
def http = new HttpURLClient( url: 'http://api.openweathermap.org/data/2.5/' )
 
// JSON request:
def resp = http.request( path: 'weather', query: [q: 'London'] )
 
println "JSON response: ${resp.status}"
 
println "It is currently ${resp.data.weather.main[0]} in London."
println "The temperature is ${resp.data.main.temp} degrees Kelvin"
 
/* Slightly different request that returns XML */
resp = http.request( path: 'weather', query:[q: 'London', mode: 'xml'] )
 
println "\n\nXML response: ${resp.status}"
println "It is currently ${resp.data.weather.@value.text()} in London."
println "The temperature is ${resp.data.temperature.@value.text()} degrees Kelvin"
Clone this wiki locally