如何在Zuul帖子过滤器中获取响应正文? [英] How to get response body in Zuul post filter?

查看:703
本文介绍了如何在Zuul帖子过滤器中获取响应正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

post过滤器中使用Zuul作为代理时,如何读取响应正文?

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;
    }

}

推荐答案

我已经设法克服了这一点.该解决方案包括4个步骤:

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

  1. ctx.getResponseDataStream()读入ByteArrayOutputStream
  2. 将OutputStream复制到2个InputStreams.
  3. 使用其中之一进行自定义.
  4. 使用第二个重新分配上下文:context.setResponseBody(inputStream)
    • 从点1读取流会导致无法再次读取该流,因此,这种方式将传递尚未读取的新的新鲜流
  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

这篇关于如何在Zuul帖子过滤器中获取响应正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆