测试API Grails

时间:2017-03-31 16:37:37

标签: rest api grails groovy

我尝试在HTTPBuilder中从URL获取JSON,但是此代码返回一个Exception,返回此错误" Method抛出' groovy.lang.MissingPropertyException' 。例外"

static request(String path, boolean isGet){
    def myClient = new HTTPBuilder("${HOST}${path}")
    def jsonResp = [:]

    try{
        if(isGet){
            log.info "[EXAMPLE GET] ${HOST}${path}"
            myClient.get(requestContentType: ContentType.JSON){ resp, json ->
                jsonResp = resp
            }
        }
    }catch(Exception e){
        println "erro: "
        log.info "[EXAMPLE ERROR]: ${e.message}"
        println(e.message)
    }
    jsonResp
}

1 个答案:

答案 0 :(得分:0)

MissingPropertyException是什么?

我在脚本中尝试了你的例子(有几个mod),这次返回json而不是resp,这似乎有效。

import groovy.transform.Field
import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder

@Field final String HOST = 'http://echo.jsontest.com'

def resp = request( "/name/jon", true )
println resp.toString()


def request(String path, boolean isGet){

    def myClient = new HTTPBuilder("${HOST}${path}")
    def jsonResp = [:]

    try{
        if(isGet){
            println  "[EXAMPLE GET] ${HOST}${path}"
            myClient.get(requestContentType: ContentType.JSON){ resp, json ->
            jsonResp = json
        }
    }
} 
catch(Exception e) {
      println(e.message)
    }
    jsonResp

}

输出是:

{"name":"jon"}