Groovy #2

Reading Json http response

The http-builder library is pretty useful to create http requests and responses in groovy. I was initially a bit surprised that groovy does not have this functionality built-in and had to import a separate jar.

Anyway I was trying to read a json response from the http-builder project website and the recommended sample did not work for some reason. This post provides a simple alternative.

Original (non-working) code

import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*

def url = "http://www.url.com"
def path = "/path/resource"
def outputFile = "c:/temp/result.json"
def params = [one:1, two:2]

def httpBuilder = new HttpBuilder(url)
httpBuilder.request(GET, JSON) {
uri.path = path
uri.query = params //parameters passed to the url -> ?one=1&two=2

headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
response.success = { resp, json ->
println resp.statusLine
outputFile.withWriter('UTF-8') { out -> out.println json }
}
}

The above code reads the json file, but if you open the json file in firefox with the JSONView plugin, you may get a “json is invalid” error.

Solution:

The updated solution is to read the response as a text and apply ‘application/json’ content type.


 def httpBuilder = new HttpBuilder(url)
 httpBuilder.request(GET, TEXT) {
  uri.path = path
  uri.query = params

  headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
  headers.Accept = 'application/json'
  response.success = { resp, json ->
   println resp.statusLine
   outputFile.withWriter('UTF-8') { out -> out.println json.text }
  }
}

With 1.8.3 release and built-in json support, this seems to be even easier now, though does not seem to be much fine-tuning of response success and failures.


def params = [one:1, two:2, three:3]
def paramString = query.collect { "$it.key=$it.value" }.join("&")
def url = site + path + "?" + paramString
def jsonResult = new URL(url).text

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: