lunedì 8 settembre 2014

How to use HttpBuilder in Grails apps

Do you need to perform some http calls from your Grails application? The best way is to use the powerful HttpBuilder groovy library.

You can find a lot of example about how to use it, and generally all these examples will rely on Grab, but the best way to use within your projects, is to add it to your BuildConfig file.

Here it is the snippet you should use. Add this to BuildConfig dependency section:

compile "org.codehaus.groovy.modules.http-builder:http-builder:0.7"

Super easy! You can find these information simply looking at the Download section of HttpBuilder documentation. Then in your controller or service you can use the example code simply importing all the needed classes.

import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import groovyx.net.http.ContentType
import groovyx.net.http.AsyncHTTPBuilder
import static groovyx.net.http.ContentType.JSON
...
def http = new HTTPBuilder('http://www.google.com')
    http.get( path : '/search',
        contentType : ContentType.TEXT,
        query : [q:'Groovy'] ) { resp, reader ->
            println "response status: ${resp.statusLine}"
            println 'Headers: -----------'
            resp.headers.each { h ->
                println " ${h.name} : ${h.value}"
            }
            println 'Response data: -----'
            System.out << reader
            println '\n--------------------'
}


Be careful to specify ContentType.TEXT which is slightly different from what stated in the documentation.
Now that you have read my article, i would like to show you another thing: i've developed an app to help increase customers registration and customers conversion.

You can find it at appromocodes.com

Nessun commento:

Posta un commento