How to get response body in Zuul post filter?

As you can see in this example, you have two methods available to extract the response body:

1- ctx.getResponseBody();

2- ctx.getResponseDataStream();

You have to check which one is not null and use that one.


I've managed to overcome this. The solution consists of 4 steps:

  1. Read ctx.getResponseDataStream() into a ByteArrayOutputStream
  2. Copy OutputStream to 2 InputStreams.
  3. Use one of it for your custom purposes.
  4. Use the second to reassign to context: context.setResponseBody(inputStream)
    • reading stream from point 1 would cause that the stream cannot be read again, so this way you're passing a new fresh stream that wasn't read yet

If someone is struggling with compressed answer, here's the solution I used:

// Read the compressed response
RequestContext ctx = RequestContext.getCurrentContext();
InputStream compressedResponseDataStream = ctx.getResponseDataStream();
try {
    // Uncompress and transform the response
    InputStream responseDataStream = new GZIPInputStream(compressedResponseDataStream);
    String responseAsString = StreamUtils.copyToString(responseDataStream, Charset.forName("UTF-8"));
    // Do want you want with your String response
    ...
    // Replace the response with the modified object
    ctx.setResponseBody(responseAsString);
} catch (IOException e) {
    logger.warn("Error reading body", e);
}

Thanks for suggestion, this is the code I used that works.

try (final InputStream responseDataStream = ctx.getResponseDataStream()) {
   final String responseData = CharStreams.toString(new InputStreamReader(responseDataStream, "UTF-8"));
   ctx.setResponseBody(responseData);
} catch (IOException e) {
   logger.warn("Error reading body",e);
}