如何读取和修改spring云网关过滤器中的请求体?有人能帮我吗?



我能够在下面的过滤器中读取请求参数。我想改变其中一个参数怎么做呢?我使用的是春云版本2020.0.0

@Component
public class ReadRequestBodyFilter extends AbstractGatewayFilterFactory<ReadRequestBodyFilter.Config>{
  public static class Config {}
  
  public ReadRequestBodyFilter() {
    super(Config.class);
  }
  @Override
  public GatewayFilter apply(Config config) {
    return (exchange, chain) -> {
      String cachedBodyAttribute = exchange.getAttribute("cachedRequestBodyObject");
      System.out.println("cachedBodyAttribute-->"+cachedBodyAttribute);
      return chain.filter(exchange);
  };
  }
}

ModifyRequestBodyGatewayFilterFactory可用于更改请求主体

@Override
public GatewayFilter apply(Config config) {
    return (exchange, chain) -> {
        String cachedBodyAttribute = exchange.getAttribute("cachedRequestBodyObject");
        System.out.println("cachedBodyAttribute-->"+cachedBodyAttribute);
        
        // modify requestData
        String newRequestData = changeRequestData(requestData); 
        
        ModifyRequestBodyGatewayFilterFactory.Config modifyRequestConfig = new ModifyRequestBodyGatewayFilterFactory.Config()
                .setContentType(ContentType.APPLICATION_JSON.getMimeType()) // change content type ... 
                .setRewriteFunction(String.class, String.class, (exchange, originalRequestBody) -> Mono.just(newRequestData))
            
        return new ModifyRequestBodyGatewayFilterFactory().apply(modifyRequestConfig).filter(exchange, chain);
    };
}

相关内容

  • 没有找到相关文章

最新更新