【问题标题】:How to retrieve http get response as a complete json String in groovy using httpbuilder如何使用httpbuilder在groovy中检索http get响应作为完整的json字符串
【发布时间】:2017-06-09 23:38:52
【问题描述】:

我想使用 GET 请求的响应 json 作为另一个请求的输入。为此,我收到的响应应该是正确的 json 格式。我正在使用 HttpBuilder 来执行此操作。

    HTTPBuilder http = new HTTPBuilder(urlParam, ContentType.JSON);
    http.headers.Accept = ContentType.JSON;
    http.parser[ContentType.JSON] = http.parser.'application/json'

    return http.request(GET) {              
        response.success = {resp, json ->
            return json.toString()
        }

当我返回 json.toString() 时,它不是一个格式良好的 json。我如何做到这一点。当我点击我的获取网址时,我看到了整个 json,但没有使用上面的代码。感谢您的帮助。

【问题讨论】:

    标签: json groovy http-get httpbuilder


    【解决方案1】:

    groovy.json.JsonOutput:

    HTTPBuilder http = new HTTPBuilder('http://date.jsontest.com/', ContentType.JSON);
    http.headers.Accept = ContentType.JSON
    http.parser[ContentType.JSON] = http.parser.'application/json'
    http.request(Method.GET) {
        response.success = { resp, json ->
            println json.toString()         // Not valid JSON
            println JsonOutput.toJson(json) // Valid JSON
            println JsonOutput.prettyPrint(JsonOutput.toJson(json))
        }
    }
    

    结果:

    {time=09:41:21 PM, milliseconds_since_epoch=1497303681991, date=06-12-2017}
    {"time":"09:41:21 PM","milliseconds_since_epoch":1497303681991,"date":"06-12-2017"}
    {
        "time": "09:41:21 PM",
        "milliseconds_since_epoch": 1497303681991,
        "date": "06-12-2017"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 2012-10-13
      • 2018-05-13
      • 2016-07-01
      • 1970-01-01
      相关资源
      最近更新 更多