我正在编写一个Grails应用程序,我希望控制器能够使用POST方法访问其他API,然后使用响应来生成用户看到的页面。但是我无法找到有关在Grails中发布到另一个页面并接收响应的正确术语。如果您能提供教程或解答,例如“这被称为...”,我将不胜感激。
OtherApiService
或某种实用程序来抽象你与外部服务的接口。将所有与该外部服务通信的代码放在一个地方;这样你就可以模拟你的集成组件,并使其他所有测试变得简单。如果你将其作为一个服务来完成,那么你还可以扩展,比如说,如果你想开始在自己的应用程序中存储来自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}"
}
}
你也许想要查看这个链接,里面有一些巧妙的技巧。它包含了一个使用POST方法的示例。