需求
原始请求体body
{
"uri":"/xxx",
"a":"xxx",
"b":"xxx"
}
路由转发到服务A的 /xxx接口 请求参数body
{
"c":"yyy",
"d":"xxx"
}
实现
新建一个pre filter,将参数 a、 b 转换成 c 、d
@Override
public Object run() throws ZuulException {
RequestContext requestContext = RequestContext.getCurrentContext();
....
//传递uri
requestContext.addZuulRequestHeader("uri", "/xxx");
//修改请求body
byte[] reqBodyBytes = "转换后的body json字符串".getBytes(StandardCharsets.UTF_8);
requestContext.setRequest(new HttpServletRequestWrapper(request){
@Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStreamWrapper(reqBodyBytes);
}
@Override
public int getContentLength() {
return reqBodyBytes.length;
}
@Override
public long getContentLengthLong() {
return reqBodyBytes.length;
}
});
....
再新建一个 route filter 转发请求到服务A
@Override
public Object run() {
RequestContext context = RequestContext.getCurrentContext();
...
RibbonCommandContext commandContext = buildCommandContext(context);
RibbonCommandContext realCommandContext = new RibbonCommandContext(commandContext.getServiceId(),
commandContext.getMethod(), context.getZuulRequestHeaders().get("uri"),
commandContext.getRetryable(), commandContext.getHeaders(), commandContext.getParams(),
commandContext.getRequestEntity(), commandContext.getRequestCustomizers(),
commandContext.getContentLength(), commandContext.getLoadBalancerKey());
RibbonCommand command = this.ribbonCommandFactory.create(realCommandContext);
ClientHttpResponse response = command.execute();
...
}
注意:本文归作者所有,未经作者允许,不得转载