简体   繁体   English

如何使用zuul将响应主体提取到后过滤器中

[英]How to extract the response body into post filter using zuul

I'm working on a POC i need to use zuul as a sever to route 2 routes first will run normally but it has a custom post filter which will send another request to other api using some data of the response of the first requet, so need to extract the response body of the first request into my custom post filter and get some specific attributes but i can not find the response as it always be null but the status code is 200. how can i wait and get a value of specific attribute from the response and get the actual status code not just 200 as default value.我正在处理一个 POC 我需要使用 zuul 作为服务器来路由 2 条路由,首先将正常运行,但它有一个自定义后过滤器,它将使用第一个请求的响应的一些数据向其他 api 发送另一个请求,所以需要将第一个请求的响应正文提取到我的自定义帖子过滤器中并获取一些特定属性,但我找不到响应,因为它始终为空但状态代码为 200。我如何等待并获取特定属性的值从响应中获取实际状态代码,而不仅仅是 200 作为默认值。

i tried to make this implementation using cloud gateway but i reached the same point of disability of extracting the response.我试图使用云网关来实现这个实现,但我达到了提取响应的相同点。 also i tried to make a response decorator but it failed too.我也尝试制作一个响应装饰器,但它也失败了。

@Component
public class AddResponseHeaderFilter extends ZuulFilter {
@Override
public String filterType() {
    return "post";
}

@Override
public int filterOrder() {
    return 1;
}

@Override
public boolean shouldFilter() {
    return true;
}

@Override
public Object run() {
    System.out.println("this is my filter");
    RequestContext context = RequestContext.getCurrentContext();
    HttpServletRequest request = new HttpServletRequestWrapper(context.getRequest());
    System.out.println(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
    HttpServletResponse servletResponse = context.getResponse();
    // return an address only
    System.out.println(context.getResponseBody().toString());
    servletResponse.addHeader("X-Foo", UUID.randomUUID().toString());
    return null;
}
}

RequestContext.getCurrentContext().getResponseDataStream()对我来说很好用,我也可以操作响应。

import java.nio.charset.Charset;
import org.springframework.util.StreamUtils;
    
 RequestContext ctx = RequestContext.getCurrentContext();
     HttpServletRequest request = ctx.getRequest();
    String requestLog = StreamUtils.copyToString(request.getInputStream(), 
    Charset.forName("UTF-8"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM