在我的应用程序中,我使用 netflix zuul
将请求从一个微服务(网关)路由到另一个微服务。请求路由正常,但我还想在请求正文中引入一些参数,然后再将其路由到适当的微服务。为此,我使用 Zuul 预过滤器,如下所示。
public class SimpleFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogger(SimpleFilter.class);
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
try {
RequestContext context = RequestContext.getCurrentContext();
InputStream in = (InputStream) context.get("requestEntity");
if (in == null) {
in = context.getRequest().getInputStream();
}
String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
// body = "request body modified via set('requestEntity'): "+ body;
body = body.toUpperCase();
context.set("requestEntity", new ByteArrayInputStream(body.getBytes("UTF-8")));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return null;
}
}
现在我只是尝试将正文更改为大写,但此请求路由到的微服务未收到修改后的正文(大写)。相反,它会收到原始的。难道我做错了什么。任何帮助,将不胜感激。谢谢!!
最佳答案
能够执行以下操作 - 将 GET 请求转换为 POST 请求,并将正文内容添加到(代理的)POST 请求。
public Object run() throws ZuulException {
RequestContext context = RequestContext.getCurrentContext();
context.addZuulRequestHeader("Content-Type", "application/x-www-form-urlencoded");
String body = String.format("a=%s&b=%s", a, b);
final byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
context.setRequest(new HttpServletRequestWrapper(context.getRequest()) {
@Override
public ServletInputStream getInputStream() {
return new ServletInputStreamWrapper(bytes);
}
@Override
public int getContentLength() {
return bytes.length;
}
@Override
public long getContentLengthLong() {
return bytes.length;
}
@Override
public String getMethod() {
return "POST";
}
});
return null;
}
关于java - 在 Zuul 预过滤器中修改请求正文不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45412149/