Springboot: Modify incoming Web service response

Viewed 269

I'm working on a springboot service currently and it needs to have the ability to modify the incoming response body received from various web service calls made by itself.

I googled around a lot and could find info about servlet filters, spring interceptors etc. But all of them sit between this service and its calling clients.

But I'm looking for a component which can sit between this service and the other services that it calls. The closest one I could find was spring's ClientHttpRequestInterceptor, but it doesn't seems to have the ability to modify response body.

  1. Client apps ---> 2. My Springboot service. ---> 3. Other web services

I need to have a component between 2 and 3 here.

Can someone please shed some light on this? Thank you.

P.S: Also I know jaxrs ClientRequestFilter does the trick, but I need a solution for spring RestTemplate based service calls and not for jaxrs based.

2 Answers

In Spring RestTemplate allows us to add interceptors that implement ClientHttpRequestInterceptor interface .

The intercept(HttpRequest, byte[], ClientHttpRequestExecution) method of this interface will intercept the given request and return the response by giving us access to the request,

ClientHttpRequestExecution argument to do the actual execution, and pass on the request to the subsequent process chain

public class BodyInterceptor
  implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(
      HttpRequest request, 
      byte[] body, 
      ClientHttpRequestExecution execution) throws IOException {

        ClientHttpResponse response = execution.execute(request, body);
        response.getHeaders().add("Iphone_version", "proX");
        return response;
    }
}

Spring AOP can help in your scenario. It can act as a component before invoking another controller or component.

Related