【发布时间】:2014-10-17 17:10:24
【问题描述】:
如何在 Grails 2.4.3 中使用 RESTful Web 服务。我还需要使用基本身份验证。
你会认为这个问题已经有了很好的答案,但我真的很难找到答案。许多答案将我指向 Grails rest 插件的方向,我已经尝试过但无法为我工作。我想我可能只是在处理文档并错误地使用它。
【问题讨论】:
标签: rest grails groovy basic-authentication
如何在 Grails 2.4.3 中使用 RESTful Web 服务。我还需要使用基本身份验证。
你会认为这个问题已经有了很好的答案,但我真的很难找到答案。许多答案将我指向 Grails rest 插件的方向,我已经尝试过但无法为我工作。我想我可能只是在处理文档并错误地使用它。
【问题讨论】:
标签: rest grails groovy basic-authentication
我找到了REST Client Builder Plugin,它有更好的文档记录,对我来说效果更好。感谢 Graeme Rocher !这是一个简单的示例,希望对其他人有所帮助。
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'
}
}
}
这是测试类。
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
}
}
返回的对象resp 是ResponseEntity 类的一个实例。
我真的希望这会有所帮助。如果有更好的示例,请发布指向它们的链接。谢谢!
【讨论】:
是的,您可以传递 UrlTemplate 样式的字符串和要替换的名称/值对 url 参数的映射。 此外,还有另一个 Auth 标头的快捷方式可以自动编码……所以
def urlTemplate = "https://foo.com/batch/{id}"
def params = [id: $id]
def resp = new RestBuilder().get(urlTemplate, params) {
auth username, password
}
【讨论】: