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.
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.
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 .
RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers. setAccept(Collections. singletonList(MediaType. APPLICATION_JSON)); HttpEntity<String> httpEntity = new HttpEntity<>("some body", headers); restTemplate.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With