Punter Vicky
Punter Vicky

Reputation: 17042

Spring ClientHttpRequestInterceptor

I have the below listed loggingInterceptor in my spring boot app. This interceptor is being called whenever a REST service invoked. I see the first 2 sysout statement being printed immediately and 3rd sysout statement is printed after the REST call is made. Is the REST call made only when getBody() is called? Please can you explain how this works? Thanks.

public class LoggingInterceptor implements ClientHttpRequestInterceptor { 
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        System.out.println(" Before Calling Execute in LoggingInterceptor "  + new Date());
        ClientHttpResponse response = execution.execute(request, body);
        System.out.println(" After Calling Execute in LoggingInterceptor "  + new Date());
        InputStream responseStream = response.getBody();
        System.out.println(" After getBody() "  + new Date());
    }  
}

Upvotes: 0

Views: 3186

Answers (1)

Ashwini Rao
Ashwini Rao

Reputation: 555

Here are my two cents on this.

This is due to the fact that ClientHttpRequestInterceptor is an interceptor for request and acts as a proxy.Now,this means it should be pretty much have handle on modifying requests and and the sending the response as needed.

Hence,when the below is executed :

ClientHttpResponse response = execution.execute(request, body);

the response is neither committed nor the request is fired,but is just buffered for modification if any,as is evident from the class :

class InterceptingClientHttpRequest extends AbstractBufferingClientHttpRequest { .. ..}

So,when you do below :

InputStream responseStream = response.getBody();

The buffered request fires the request ,gets the response output stream.

Upvotes: 1

Related Questions