我正在将 groovy 脚本从httpbuilder更新为httpbuilder-ng。这些脚本与各种 Web 服务交互以获取消息。我希望最好使用杰克逊将响应解析为对象。但是,我似乎无法像在 httpbuilder 中那样获得原始 json 响应,因为在所有情况下,httpbuilder-ng 都会自动解析为惰性映射。
使用 httpbuilder 的旧实现允许您使用 body.text 方法获取原始 json 字符串,而无需将其解析为惰性映射。然后这可以与 Jackson 中的 ObjectMapper 一起使用来创建我的 POJO。但是,httpbuilder-ng 似乎不支持这一点。
我已经尝试过这里获取原始 json 的方法,但是 body.text 方法在我使用的版本 1.03 中似乎不起作用http://coffeaelectronica.com/blog/2016/httpbuilder-ng-demo。 .html _
我还尝试添加我自己的自定义编码器来覆盖 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
}
}