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

问题描述 投票:0回答:1

我正在尝试在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;
    }
} 

这是我正在做的请求:

这是我收到的回复:

filter netflix-zuul netflix
1个回答
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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.