Login required
Download

REST Client

(0)
Author(s): aalmiray
Current Release: 0.3
Grails Version: 1.2.0 > *
Tags rest
grails install-plugin rest

Description

The REST plugin enables the usage of HTTPBuilder on a Grails application.

Usage

The plugins will inject the following dynamic methods:

  • withHttp(Map params, Closure stmts) - executes stmts using a @HTTPBuilder@
  • withAsyncHttp(Map params, Closure stmts) - executes stmts using an @AsyncHTTPBuilder@
  • withRest(Map params, Closure stmts) - executes stmts using a @RESTClient@

Examples

Taken from HttpBuilder's Simplified GET Request

withHttp(uri: "http://www.google.com") {
   def html = get(path : '/search', query : [q:'Groovy'])
   assert html.HEAD.size() == 1
   assert html.BODY.size() == 1
}

Notice that you can call HTTPBuilder's methods inside @stmts@, the current HTTPBuilder is set as the closure's delegate. The same holds true for the other dynamic methods.

AsyncHTTPBuilder

import static groovyx.net.http.ContentType.HTML

withAsyncHttp(poolSize : 4, uri : "http://hc.apache.org", contentType : HTML) { def result = get(path:'/') { resp, html -> println ' got async response!' return html } assert result instanceof java.util.concurrent.Future

while (! result.done) { println 'waiting...' Thread.sleep(2000) }

/* The Future instance contains whatever is returned from the response closure above; in this case the parsed HTML data: */ def html = result.get() assert html instanceof groovy.util.slurpersupport.GPathResult }

All dynamic methods will create a new http client when invoked unless you define an id: attribute. When this attribute is supplied the client will be stored as a property on the instance's metaClass. You will be able to access it via regular property access or using the id: again.

class FooController {
  def loginAction = {
    withRest(id: "twitter", uri: "http://twitter.com/statuses/") {
      auth.basic model.username, model.password
    }
  }

def queryAction = { withRest(id: "twitter") { def response = get(path: "followers.json") // … } /* alternatively def response twitter.get(path: "followers.json") */ } }

Configuration

Dynamic method injection

Dynamic methods will be added to controllers by default. You can change this setting by adding a configuration flag in@Config.groovy@

grails.rest.injectInto = ["Controller", "Service"]

Proxy settings

You can apply proxy settings by calling @setProxy(String host, int port, String scheme)@on the client/builders at any time. You can also take advantage of the proxy: shortcut

withHttp(uri: "http://google.com", proxy: [host: "myproxy.acme.com", port: 8080, scheme: "http"])

This shortcut has the following defaults

  • @port:@ = 80
  • @scheme:@ = http
Meaning most of the times you'd only need to define a value for @host:@