Question

I am developing a restful webservice using grails for first time and I following the chapter 13 in the grails documentation for setting up a simple response to a GET request.

The thing i do not get is setting up HTTPBuilder for creating a client which makes a get request. I have downloaded the jar httpbuilder, The Restful client is defined as follows

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

def http = new HTTPBuilder("http://localhost:8080/amazon")

http.request(Method.GET, JSON) { url.path = '/book/list' response.success = { resp, json -> for (book in json.books) { println book.title } } }

So the code they have customized for the client is it a new HTTPBuilder class defined ? if yes where do we need to define this class

Right now the routing of URL to show def in my controller is not happeining.

Thanks

Was it helpful?

Solution

I'm not sure what exactly you are trying to do since I don't know what your localhost service is supposed to return. Since you're looking for books, here's an example using Google's book search that may be of help. I wrote so that you can run in the Groovy console if you want, but will work in grails as well.

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.2' )

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.JSON
import static groovyx.net.http.Method.GET

def http = new HTTPBuilder("https://www.googleapis.com")

http.handler.failure = { resp, json ->
    println "it broke ${resp} ${json}"
}
http.get(path: '/books/v1/volumes', query:[q:'quilting']) { resp, json ->
    if (resp.status == 200) {
        json?.items.each {book ->
            println "${book?.volumeInfo?.title}"
        }
    } else {
        return [error:"Did not return a proper response: ${resp.status}"]
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top