Instruct Groovy HTTPBuilder to handle a JSON response with wrong content type

While developing a utility script to monitor my mobile data consumed, I found a problem with

the response I was getting from the server. It content-type was set to ‘text/json’ instead of ‘application/json’, ‘application/javascript’ or ‘text/javascript’ wich are the content types used by HTTPBuilder to parse a response as JSON.

To solve this problem, one must add a new content type to the ParserRegistry and parse the response.

There are two ways to do it:

1
2
3
4
5
6
def httpBuilder = new HTTPBuilder(baseUrl)
 
httpBuilder.parser.'text/json' = { resp ->
   def bufferedText = resp.entity.content.getText( ParserRegistry.getCharset( resp ) ).trim()
   return new JsonSlurper().parseText( bufferedText )
}

The second ( reuse default )

1
2
def httpBuilder = new HTTPBuilder(baseUrl)
httpBuilder.parser.'text/json' = httpBuilder.parser.'application/json'

Now everything works again.

See you

2 Responses to “ Instruct Groovy HTTPBuilder to handle a JSON response with wrong content type ”

  1. Sorry, no hablo espanol.

    It seems that text/json is the wrong content-type. It should be either «application/json» or «text/x-json».

    So, you can tell your Server-Side developers to fix the value for «content-type» in the headers before they stream «application/json» it to you. 🙂

    De nada,
    Stuart

    • Hi Stuart,

      I know, but the server side is not under my control, this is why I had to solve this issue in my script.
      Thanks for your comment.

      Alfonso

Comments are closed.