3

I'm updating groovy scripts from httpbuilder to httpbuilder-ng. These scripts interact with various webservices to get messages. I'm looking to parse the responses preferably using Jackson into objects. However, I can't seem to get the raw json response like I could in httpbuilder as httpbuilder-ng auto parses into a lazymap in all cases.

The old implementation using httpbuilder allowed you to use the body.text method to get the raw json string without it being parsed into a lazymap. This could then be used with ObjectMapper in Jackson to create my POJO's. However, httpbuilder-ng doesn't seem to support this.

I have already tried the method here for getting the raw json, but the body.text method does not seem to work in version 1.03 that I'm using http://coffeaelectronica.com/blog/2016/httpbuilder-ng-demo.html.

I have also tried to add my own custom encoders to override Groovy's default creation of JSON objects without any success. It is supposedly possible as detailed in the wiki https://http-builder-ng.github.io/http-builder-ng/asciidoc/html5/. If anyone has a code snippet of how to do this it would be appreciated!

Old httpbuilder code:

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

new http-builder-ng code:

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

Update

Found the solution. It was to add a custom parser and a closure using the FromServer.inputstream.text method.

def text = httpBuilder.get {
        request.uri.path = '/blah/plugins/blah/queues'
        response.parser('application/json') { ChainedHttpConfig cfg, FromServer fs ->
            String text = fs.inputStream.text
        }
    }
alexnanrick
  • 31
  • 1
  • 3

0 Answers0