【问题标题】:Test API Grails测试 API Grails
【发布时间】:2017-03-31 16:37:37
【问题描述】:

我尝试从 HTTPBuilder 的 URL 获取 JSON,但此代码返回异常,返回此错误“方法抛出了 '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
}

【问题讨论】:

    标签: rest api grails groovy


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 2012-09-30
      相关资源
      最近更新 更多