Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Read and modify request body in spring cloud gateway filters? can anyone help me

I am able to read request parameters in the below filter . I want to change one of the parameters how can I do that? I am using spring cloud version 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);
  };
  }

}
like image 787
meghana manjunath Avatar asked Nov 23 '25 22:11

meghana manjunath


1 Answers

ModifyRequestBodyGatewayFilterFactory can be used to change the body of a request

@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);
    };
}
like image 135
baba Avatar answered Nov 28 '25 17:11

baba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!