gpt4 book ai didi

filter - 将新字段添加到来自 Netflix Zuul 预过滤器的请求正文

转载 作者:行者123 更新时间:2023-12-04 00:33:08 25 4
gpt4 key购买 nike

我正在尝试在 Zuul 预过滤器中向请求的主体添加一个新字段。

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

我可以应用大写等转换,甚至可以完全修改请求,唯一不方便的是我无法修改长度超过原始长度的body请求的内容 body 的要求。

这是我的过滤器的实现:

@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

最佳答案

使用 PrefixRequestEntityFilter 的实现,我能够从 sample-zuul-examples 获得我想要的东西:

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

关于filter - 将新字段添加到来自 Netflix Zuul 预过滤器的请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47811480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com