【问题标题】:Grails 2.4.3: Consume a REST ServiceGrails 2.4.3:使用 REST 服务
【发布时间】:2014-10-17 17:10:24
【问题描述】:

如何在 Grails 2.4.3 中使用 RESTful Web 服务。我还需要使用基本身份验证。

你会认为这个问题已经有了很好的答案,但我真的很难找到答案。许多答案将我指向 Grails rest 插件的方向,我已经尝试过但无法为我工作。我想我可能只是在处理文档并错误地使用它。

【问题讨论】:

    标签: rest grails groovy basic-authentication


    【解决方案1】:

    我找到了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
        }
    }
    

    返回的对象respResponseEntity 类的一个实例。

    我真的希望这会有所帮助。如果有更好的示例,请发布指向它们的链接。谢谢!

    【讨论】:

    • 除了url字符串连接之外,有没有办法传递url参数?
    • 对上一个问题有任何答案吗?
    • 我没有看到任何其他的方式,但我看起来不是很努力。
    【解决方案2】:

    是的,您可以传递 UrlTemplate 样式的字符串和要替换的名称/值对 url 参数的映射。 此外,还有另一个 Auth 标头的快捷方式可以自动编码……所以

        def urlTemplate = "https://foo.com/batch/{id}"
        def params = [id: $id]
    
        def resp = new RestBuilder().get(urlTemplate, params) {
           auth username, password
        }
    

    【讨论】:

      猜你喜欢
      • 2014-11-20
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多