When we want to access a RESTful webservice with Groovy we can use HTTPBuilder. The HTTPBuilder library also contains the RESTClient class. This class has a simple API to access RESTful webservices. For example if we want to POST an XML message to a RESTful webservice we can use the post()
method. Because we set the request content type to XML we have a StreamingMarkupBuilder object we can use to build our XML.
The response object is automatically read by the XmlSlurper class, so we have access to the resulting GPathResult object. The following code snippet shows a simple POST to the RESTful webservice of Solr:
import groovyx.net.http.RESTClient import groovy.util.slurpersupport.GPathResult import static groovyx.net.http.ContentType.XML @Grab(group='org.codehaus.groovy', module='http-builder', version='0.5.0-SNAPSHOT') def samplePOST() { solr = new RESTClient('http://localhost:8080/solr/update') def response = solr.post( contentType: XML, requestContentType: XML, body: { add { doc { field(name:"id", "SOLR1000") field(name:"name", "Solr, the Enterprise Search Server") field(name:"manu", "Apache Software Foundation") field(name:"cat", "software") field(name:"cat", "search") field(name:"features", "Advanced Full-Text Search Capabilities using Lucene") field(name:"features", "Optimized for High Volume Web Traffic") field(name:"features", "Standards Based Open Interfaces - XML and HTTP") field(name:"features", "Comprehensive HTML Administration Interfaces") field(name:"features", "Scalability - Efficient Replication to other Solr Search Servers") field(name:"features", "Flexible and Adaptable with XML configuration and Schema") field(name:"features", "Good unicode support: héllo (hello with an accent over the e)") field(name:"price", "0") field(name:"popularity", "10") field(name:"inStock", "true") field(name:"incubationdate_dt", "2006-01-17T00:00:00.000Z") } } } ) println "Solr response status: ${response.status}" assert response.success assert response.status == 200 assert response.data instanceof GPathResult assert response.data.lst.int[0].@name == 'status' } samplePOST()