Grails 2.4.3:使用REST服务 [英] Grails 2.4.3: Consume a REST Service
问题描述
你会认为这个问题已经很好的回答了,但我真的很努力地找到一个。许多答案都指向了Grails休息插件的方向,我尝试过,但无法为我工作。我认为我可能只是在努力处理文档并将其用于错误。
解决方案//grails.org/plugin/rest-client-builderrel =noreferrer> REST客户端生成器插件,它的记录效果更好,对我来说效果更好。感谢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 {
voidtest get batch(){
when:
def resp = service.restart('BI1234')
then:
resp.status == HttpStatus.OK.value
}
}
返回的对象 resp
,是 ResponseEntity 课程。
我真的希望这有助于。如果有更好的例子,请发布链接。谢谢!
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!
这篇关于Grails 2.4.3:使用REST服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!