How do I consume a RESTful web service in Grails 2.4.3. I also need to use Basic Authentication.
You would think there would be an good answer to this question already, but I have really struggled to find one. Many answers point me in the direction of the Grails rest plugin, which I have tried but could not get to work for me. I think I am probably just struggling with the docs and using it wrong.
I found the REST Client Builder Plugin, which was better documented and worked much better for me. Thanks to Graeme Rocher for that! Here's a simple example that will hopefully be helpful to others.
import grails.plugins.rest.client.RestBuilder
import grails.transaction.Transactional
@Transactional
class BatchInstanceService {
def getBatch(String id) {
String url = "https://foo.com/batch/$id"
def resp = new RestBuilder().get(url) {
header 'Authorization', 'Basic base64EncodedUsername&Password'
}
}
}
And here's the test class.
import grails.test.mixin.*
import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.methods.*
import org.springframework.http.HttpStatus
import spock.lang.Specification
@TestFor(BatchInstanceService)
class BatchInstanceServiceSpec extends Specification {
void "test get batch" () {
when:
def resp = service.restart('BI1234')
then:
resp.status == HttpStatus.OK.value
}
}
The object returned, resp
, is an instance of the ResponseEntity class.
I really hope this helps. If there are better examples please post links to them. Thanks!