我正在将Groovy脚本从httpbuilder更新为httpbuilder-ng。这些脚本与各种Web服务交互以获取消息。我正在寻找最好使用Jackson解析对象的响应。但是,我似乎无法像在httpbuilder中那样获得原始的json响应,因为在所有情况下httpbuilder-ng都会自动解析为惰性映射。
使用httpbuilder的旧实现允许您使用body.text方法获取原始json字符串,而无需将其解析为惰性映射。然后可以将其与Jackson中的ObjectMapper一起使用来创建我的POJO。但是,httpbuilder-ng似乎不支持此功能。
我已经在这里尝试了获取原始json的方法,但是body.text方法在我正在使用http://coffeaelectronica.com/blog/2016/httpbuilder-ng-demo.html的1.03版中似乎不起作用。
我还尝试添加自己的自定义编码器来覆盖Groovy的JSON对象的默认创建,但没有成功。据推测,这可能在Wiki https://http-builder-ng.github.io/http-builder-ng/asciidoc/html5/中进行了详细介绍。如果有人有如何执行此操作的代码段,将不胜感激!
旧的httpbuilder代码:
def http = new HTTPBuilder("http://${proxy}.domain.ie")
http.request(GET, TEXT) {
uri.path = "/blah/plugins/blah/queues"
headers.Accept = 'application/json'
headers.'Cookie' = "token=${token}"
response.success = { resp, json ->
assert resp.status < 300
LOGGER.info("GET queues request succeeded, HTTP " + resp.status)
ObjectMapper objectMapper = new ObjectMapper()
queues = objectMapper.readValue(json, Queue[].class)
}
response.failure = { resp ->
assert resp.status >= 300
LOGGER.info("GET queues request failed, HTTP " + resp.status)
return null
}
}
新的http-builder-ng代码:
def http = configure {
request.uri = "http://${proxy}.domain.ie"
request.headers["Accept"] = "application/json"
request.headers["Cookie"] = "token=${token}"
request.contentType = TEXT
}
return http.get {
request.uri.path = "/blah/plugins/blah/queues"
response.success { FromServer fs, Object body ->
return body.text // doesn't work
}
response.failure {
return null
}
}
更新
找到了解决方案。原来是使用FromServer.inputstream.text方法添加自定义解析器和闭包。
def text = httpBuilder.get {
request.uri.path = '/blah/plugins/blah/queues'
response.parser('application/json') { ChainedHttpConfig cfg, FromServer fs ->
String text = fs.inputStream.text
}
}