好像您正在与某种RESTful Web服务集成.有REST客户端插件,挂在这里.
或者,如果没有插件,很容易做到这一点,链接在这里.
我强烈建议让你的控制器只是一个控制器.将这个外部服务的接口抽象为类OtherApiService
或某种类的实用程序.将与此外部服务通信的所有代码保存在一个位置; 这样你就可以模拟你的集成组件,并在其他地方轻松进行测试.如果您将此作为服务进行,则可以扩展,例如,您希望开始在自己的应用程序中存储API中的某些数据.
无论如何,从链接文档(第二个链接)剪切和发布,下面显示了如何将GET发送到API以及如何设置成功和失败的处理程序,以及处理请求标头和查询参数 - 这应该拥有你需要的一切.
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
def http = new HTTPBuilder( 'http://ajax.googleapis.com' )
// perform a GET request, expecting JSON response data
http.request( GET, JSON ) {
uri.path = '/ajax/services/search/web'
uri.query = [ v:'1.0', q: 'Calvin and Hobbes' ]
headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
// response handler for a success response code:
response.success = { resp, json ->
println resp.statusLine
// parse the JSON response object:
json.responseData.results.each {
println " ${it.titleNoFormatting} : ${it.visibleUrl}"
}
}
// handler for any failure status code:
response.failure = { resp ->
println "Unexpected error: ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
Run Code Online (Sandbox Code Playgroud)
对于一些漂亮的技巧,您可能还想看看这个.有一个POST方法的例子.
归档时间: |
|
查看次数: |
6795 次 |
最近记录: |