Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response from a POST request in Groovy RESTClient is missing data

I am using groovy RESTClient 0.6 to make a POST request. I expect an XML payload in the response. I have the following code:

def restclient = new RESTClient('<some URL>')
def headers= ["Content-Type": "application/xml"]
def body= getClass().getResource("/new_resource.xml").text
/*
 If I omit the closure from the following line of code
 RESTClient blows up with an NPE..BUG?
*/
def response = restclient.post(
                            path:'/myresource', headers:headers, body:body){it}
 println response.status //prints correct response code
 println response.headers['Content-Length']//prints 225
 println response.data //Always null?!

The response.data is always null, even though when I try the same request using Google chrome's postman client, I get back the expected response body. Is this a known issue with RESTClient?

like image 636
The Governor Avatar asked Jan 12 '23 19:01

The Governor


1 Answers

The HTTP Builder documentation says that data is supposed to contain the parsed response content but, as you've discovered, it just doesn't. You can, however, get the parsed response content from the reader object. The easiest, most consistent way I've found of doing this is to set the default success and failure closures on your RESTClient object like so:

def restClient = new RESTClient()
restClient.handler.failure = { resp, reader ->
    [response:resp, reader:reader]
}
restClient.handler.success = { resp, reader ->
    [response:resp, reader:reader]
}

You'll get the same thing on success and failure: a Map containing the response (which is an instance of HttpResponseDecorator) and the reader (the type of which will be determined by the content of the response body).

You can then access the response and reader thusly:

def map = restClient.get([:]) // or POST, OPTIONS, etc.
def response = map['response']
def reader = map['reader']

assert response.status == 200
like image 79
Sam T. Avatar answered Jun 08 '23 01:06

Sam T.