1

好吧,我是 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 应用程序。关于如何做同样的任何建议?

4

3 回答 3

1
  1. 在 BuildConfig 中定义依赖(除了 groovy 依赖)
  2. 将脚本内容复制到服务

可能的扩展:

  1. 使用grails rest 插件grails rest-client-builder 插件而不是 http-builder
于 2013-08-28T09:37:05.490 回答
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
    }
}
于 2014-01-08T10:15:56.547 回答
0

将逻辑放入 Service 对象将使您能够进行依赖注入,这是 Grails 服务的本机。

AsyncHTTPBuilder此外,如果您的应用程序有很多用户尝试发出请求 ,您应该考虑使用。

于 2014-01-08T03:50:36.597 回答