Issue
I'm having a weird problem, i'm using tokens on Microservice enviroment, I need to call another service with the token already generated.
Call to other service on a Client class... There is the method.
return restTemplate.exchange(URL_REST_METHOD,
HttpMethod.GET,
httpEntity, //HEADER OK
SubscriptionDto.class,
subscriptionId);
To do things easy, I get the previous request, get the token and added to current request.
public class HeaderLoginInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpServletRequest previousRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
if(previousRequest.getHeader(AUTHORIZATION) != null){
request.getHeaders().add(AUTHORIZATION, previousRequest.getHeader(AUTHORIZATION));
}
return execution.execute(request, body);
}
}
I attach this interceptor to the Bean RestTemplate
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors
= restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) {
interceptors = new ArrayList<>();
}
interceptors.add(new HeaderLoginInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
The weird thing, after the execution, I see a defect on Authorization header:
Correct one:
Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhdWQiOiJBZGlkYXMgQ2hhbGxlbmdlIiwic3...
Weird after:
Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhdWQiOiJBZGlkYXMgQ2hhbGxlbmdlIiwic3...
I try adding the token directly before call exchange method, same result.
HttpServletRequest previousRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpHeaders headers = new HttpHeaders();
headers.addAll((MultiValueMap<String, String>) previousRequest.getHeaderNames());
HttpEntity<?> httpEntity = new HttpEntity<>(new HttpHeaders());
In both cases, after call method restTemplate.exchange(...) it corrupts.
Any ideas?
Thanks a lot
Solution
After a lot of research, the problem is related to charset of RestTemplate.
If I add this line on @Bean configuration, the problem is solved:
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
/*** THE SAVERY LINE ***/
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
/*** ***/
List<ClientHttpRequestInterceptor> interceptors
= restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) {
interceptors = new ArrayList<>();
}
interceptors.add(new HeaderLoginInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
After that, works normally.
Answered By - Ignacio Escursell