Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling execution.execute() twice in RestTemplate interceptor

I have to integrate with external service that requires access token to be sent with each requests. Access token has a short expiration time (only a few hours). I've decided to use access token in optimistic way. I'm going to call external service with current token. I case of getting 401 I'm going to refresh the token and call the external API one more time.

I've decided to use ClientHttpRequestInterceptor to implement described retry mechanism.

public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
   ClientHttpResponse response = execution.execute(request, body);
   if(response.getStatusCode() == UNAUTHORIZED) {
       refreshToken();
       updateToken(request);
       response = execution.execute(request, body);
   }
   return response;
}

I have tested it and it works, but is it allowed to call execution.execute() twice? I haven't found any information that it's forbidden, but from the other hand I haven't seen such code as well.

like image 548
pmajcher Avatar asked Jul 31 '17 09:07

pmajcher


People also ask

What is interceptor in RestTemplate?

Interceptors are generally used in Spring to intercept requests of either self created end point at Controller, OR, to intercept other(3rd party) api calls done by RestTemplate.

What is RestTemplateBuilder?

public class RestTemplateBuilder extends Object. Builder that can be used to configure and create a RestTemplate . Provides convenience methods to register converters , error handlers and UriTemplateHandlers .

How do you add multiple headers to RestTemplate?

RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers. setAccept(Collections. singletonList(MediaType. APPLICATION_JSON)); HttpEntity<String> httpEntity = new HttpEntity<>("some body", headers); restTemplate.

What are interceptors in REST API?

Ad. Jakarta Restful Web Services includes an Interceptor API that allows developers to intercept request and response processing. This allows addressing some advanced concepts like authentication, caching, and compressing without polluting application code.


1 Answers

we are doing exactly the same - and having issues. This snippet of code you have there will leak connections as the original response is ignored and not closed properly. My current solution is to explicitly close it and then do the second execution. Seems to work so far but I guess it needs more evaluation.

like image 143
Witko Avatar answered Sep 21 '22 16:09

Witko