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.