Question

I want to have two interceptors for every request I do on a webservice. One for the outgoing communication, and one for the response.

I am using ClientHttpRequestInterceptor which is working for the outgoing. I am setting it as follows:

//Rest template
RestTemplate tpl = api.getRestTemplate();
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add( new OutgoingRequestInterceptor() );

tpl.setInterceptors( interceptors );

However, I want something like this interceptor for the incoming (response). I checked Spring Framework sourcecode and I couldn't find anything for this.

Any tips?

Edit:

Maybe I am confused or something is wrong in my head. Im a bit ill today.

I've the following code in my interceptor class:

@Override
public ClientHttpResponse intercept( HttpRequest request, byte[] bytes, ClientHttpRequestExecution requestExecution ) throws IOException
{
    SLog.d( "intercepted!!"+request.getURI()+". Bytes: "+bytes );
    try
    {
        Thread.sleep( 5000 );
    }
    catch ( InterruptedException e )
    {
        e.printStackTrace();
    }
    ClientHttpResponse response = requestExecution.execute( request, bytes );

    SLog.d( "Response Headers: " + response.getHeaders());


    return response;
}

Question: Is this code working for outgoing, incoming, or both? Because the log:request.getUri() is returning the destination URL.

Then, on the Response object, I get the headers sent by WebService.

So what I am sure of, is that response is actually the server response. But... How about getUri() thingy? Is it triggered before actually sending the request, or after?

Was it helpful?

Solution

Okay. After some tricky debugging, I got it.

Even though the interceptor class is called ClientHttpRequestInterceptor, it's intercepting both. Request from client, and respose from Server.

This interceptor class is something like a wrapper.

enter image description here

So...

  1. This method is the wrapper of the whole request. From BEFORE request and after the request is done.
  2. This part of the code is triggered BEFORE request is sent to webservice
  3. This part of the code ACTUALLY CONTACTS WEBSERVICE, so it "pauses" there until it gets the response from the web service.
  4. We return the response generated. Notice that if you use method response.getBody() which is an InputStream, you will consume it, so it will be null afterwards. I say that because you CAN'T directly log it. You've to mirror it first.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top