从Netflix Zuul预过滤器向请求正文添加新字段

时间:2017-12-14 10:48:59

标签: filter netflix-zuul netflix

我试图在Zuul预过滤器中为请求的主体添加新字段。

我使用了来自here的Neflix的Zuul示例项目之一,我的过滤器实现与此示例中的UppercaseRequestEntityFilter非常相似。

我能够应用大写等转换,甚至完全修改请求,唯一不方便的是我无法修改身体长度更长的请求内容而不是身体要求的原始长度。

这是我的过滤器实现:

@Component
public class MyRequestEntityFilter extends ZuulFilter {
    public String filterType() {
        return "pre";
    }

    public int filterOrder() {
        return 10;
    }

    public boolean shouldFilter() {
        RequestContext context = getCurrentContext();
        return true;
    }

    public Object run() {
        try {
            RequestContext context = getCurrentContext();
            InputStream in = (InputStream) context.get("requestEntity");
            if (in == null) {
                in = context.getRequest().getInputStream();
            }

            String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));

            body = body.replaceFirst("qqq", "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");

            // body = body.toUpperCase();

            context.set("requestEntity", new ServletInputStreamWrapper(body.getBytes("UTF-8")));
        }
        catch (IOException e) {
            rethrowRuntimeException(e);
        }
        return null;
    }
} 

这是我正在做的请求:

Request Sample

这是我收到的回复:

Response

1 个答案:

答案 0 :(得分:0)

我能够使用sample-zuul-examples中的PrefixRequestEntityFilter实现获得我想要的内容:

@Component
public class MyRequestEntityFilter extends ZuulFilter {
    public String filterType() {
        return "pre";
    }

    public int filterOrder() {
        return 10;
    }

    public boolean shouldFilter() {
        RequestContext context = getCurrentContext();
        return true;
    }

    public Object run() {
        try {
            RequestContext context = getCurrentContext();
            InputStream in = (InputStream) context.get("requestEntity");
            if (in == null) {
                in = context.getRequest().getInputStream();
            }

            String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));

            body = body.replaceFirst("qqq", "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");

            byte[] bytes = body.getBytes("UTF-8");

            context.setRequest(new HttpServletRequestWrapper(getCurrentContext().getRequest()) {
                @Override
                public ServletInputStream getInputStream() throws IOException {
                    return new ServletInputStreamWrapper(bytes);
                }

                @Override
                public int getContentLength() {
                    return bytes.length;
                }

                @Override
                public long getContentLengthLong() {
                    return bytes.length;
                }
            });

        }
        catch (IOException e) {
            rethrowRuntimeException(e);
        }
        return null;
    }
}