Reputation: 3273
I am attempting to write my own response handlers for Groovy's RESTClient (which wraps around HttpBuilder). I want to always print the response body if one is returned. However, I cannot find a consistent way to do it.
Typically a custom response handler would look like this:
def client = new RESTClient(url)
client.handler.success = { resp, reader ->
//do stuff
}
client.handler.failure = { resp, reader ->
//do stuff
throw new Exception("HTTP call failed. Status code: ${resp.getStatus()}")
}
However, what I noticed is that the variable "reader" can have a different class depending on the response. I've seen the reader be of type groovy.util.slurpersupport.NodeChild
or org.apache.http.conn.EofSensorInputStream
. I want it to be a predictable class so I can actually call the methods on this object. What's going on here?
Upvotes: 1
Views: 2469
Reputation: 3273
Setting the content type to ANY
and changing the HttpBuilder content parsers to the text parser fixed the issue. The type of reader
in the response handler is now always java.io.InputStreamReader
.
Before:
def headerMap = [:]
//populate headers
def response = client.get("headers":headerMap)
After:
client.parser.'application/xml' = client.parser.'text/plain'
client.parser.'application/xhtml+xml' = client.parser.'text/plain'
client.parser.'application/atom+xml' = client.parser.'text/plain'
client.parser.'application/json' = client.parser.'text/plain'
client.parser.'text/html' = client.parser.'text/plain'
client.parser.'application/x-www-form-urlencoded' = client.parser.'text/plain'
def headerMap = [:]
//populate headers
def response = client.get("headers":headerMap, contentType:groovyx.net.http.ContentType.ANY)
Upvotes: 4