如何检索HTTP获取响应作为一个完整的JSON字符串在groovy使用httpbuilder

如何检索HTTP获取响应作为一个完整的JSON字符串在groovy使用httpbuilder

问题描述:

我想使用GET请求的响应json作为另一个请求的输入。为此,我收到的回应应该是正确的json格式。我正在使用HttpBuilder来做到这一点。如何检索HTTP获取响应作为一个完整的JSON字符串在groovy使用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,但没有使用上面的代码。感谢您的帮助。

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