How it is possible to read a response body while using Zuul as a proxy in post
filter?
I am trying to call the code like this:
@Component public class PostFilter extends ZuulFilter { private static final Logger log = LoggerFactory.getLogger(PostFilter.class); @Override public String filterType() { return "post"; } @Override public int filterOrder() { return 2000; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); ctx.getResponseBody(); // null // cant't do this, cause input stream is used later in other filters and I got InputStream Closed exception // GZIPInputStream gzipInputStream = new GZIPInputStream(stream); return null; } }
Advertisement
Answer
I’ve managed to overcome this. The solution consists of 4 steps:
- Read
ctx.getResponseDataStream()
into a ByteArrayOutputStream - Copy OutputStream to 2 InputStreams.
- Use one of it for your custom purposes.
- 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