Grails 2.4.3: Consume a REST Service

孤街浪徒 提交于 2019-12-10 03:09:02

问题


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.


回答1:


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!




回答2:


Yes, you can pass a UrlTemplate-style string and the map of name/value pair url parameters to be substituted. In addition, there is another shortcut to Auth headers that will auto-encode... so

    def urlTemplate = "https://foo.com/batch/{id}"
    def params = [id: $id]

    def resp = new RestBuilder().get(urlTemplate, params) {
       auth username, password
    }


来源:https://stackoverflow.com/questions/25470866/grails-2-4-3-consume-a-rest-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!