2013-08-28 36 views
1

那么我是Groovy/Grails的新手。我编写了一个使用RESTClient向JIRA服务器发送HTTP POST请求的Groovy脚本。 POST请求发送JQL查询并以JSON格式接收结果。以下是完整的代码:Groovy脚本到Grails应用程序

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应用程序。有关如何做同样的建议?

回答

1
  1. 定义在BuildConfig依赖关系(除了常规的依赖性)
  2. 脚本复制内容到服务

可能延长:

  1. 使用grails rest plugingrails rest-client-builder plugin而不是http建设者
+0

感谢您的答复!非常感激。 我添加了依赖关系并将脚本复制到** Controller **。当我从Web浏览器访问控制器时,它给了我一个NullPointerException。 “消息:无法调用空对象上的方法post() 服务中发生的情况也是如此。有什么建议么? –

+0

听起来像'jiraClient'为空。值得检查,如果你正确地初始化它。 – Armand

+0

感谢您的提示!初始化时出现问题。但现在得到一个新的NullPointerException。叹!同一行,'def Issues = jiraClient.post(requestContentType:JSON,路径:uriPath,body:param)'。 “消息:null”。 –

0

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

此外,如果您的应用有许多用户试图发出请求,则应考虑使用AsyncHTTPBuilder

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 
    } 
}