我是Groovy / Grails的新手。我编写了一个Groovy脚本,它使用RESTClient向JIRA服务器发出HTTP POST请求。 POST请求发送JQL查询并以JSON格式接收结果。这是完整的代码:
import groovyx.net.http.RESTClient;
import groovyx.net.http.HttpResponseDecorator;
import org.apache.http.HttpRequest;
import org.apache.http.protocol.HttpContext;
import org.apache.http.HttpRequestInterceptor;
import groovy.json.JsonSlurper;
import static groovyx.net.http.Method.*
import static groovyx.net.http.ContentType.*
@Grab(value = 'org.codehaus.groovy:groovy-all:2.1.6',
initClass = false)
@Grapes([
@Grab(group = 'org.codehaus.groovy.modules.http-builder',
module = 'http-builder', version = '0.5.2'),
@GrabExclude('org.codehaus.groovy:groovy')
])
// connect to JIRA
def jiraApiUrl = 'http://my-jira.com/rest/api/2/'
def jiraClient = new RESTClient(jiraApiUrl);
// authentication
def basic = 'Basic ' + 'username:password'.bytes.encodeBase64().toString()
jiraClient.client.addRequestInterceptor (
new HttpRequestInterceptor() {
void process(HttpRequest httpRequest,
HttpContext httpContext) {
httpRequest.addHeader('Authorization', basic)
}
})
// http post method
def uriPath = 'search'
def param = [maxResults : 1, jql : '<jql-query>']
def Issues = jiraClient.post(requestContentType : JSON, path : uriPath, body : param)
def slurpedIssues = new JsonSlurper().parseText(Issues.data.toString())
println Issues.data.total
我需要将此脚本迁移到Grails应用。有关如何做同样的建议吗?
答案 0 :(得分:1)
可能的扩展名:
答案 1 :(得分:0)
将逻辑放入Service对象将使您能够执行依赖注入,这是grails服务的原生。
此外,如果您的应用有许多用户尝试发出请求,您应该考虑使用AsyncHTTPBuilder
。
答案 2 :(得分:0)
我坚信服务响应将直接呈现给JSON
//your controller
class AbcController{
//your action
def save() {
render(abcService.save(params) as JSON)//your service response now been rendered to JSON
}
}
//your service class class AbcService {
def save(params){
....
return something
}
}