Is it possible to create with RestTemplateBuilder an instance of RestTemplate with just the bearer header and token?
I know i can use RestTemplate exchange and set inside the HttpEntity my headers but is it possible to do something like this:
public RestTemplate getRestTemplate(){
RestTemplateBuilder builder = new RestTemplateBuilder();
return builder.build().exchange().setBearerAuth("token here"); //this is not possible
}
Hope you understand what i want to do.
As lilalinux pointed out in the comment - Authorization is the name of the header and Bearer + the token itself are the value.
@Bean(name = "myRestTemplate")
public RestTemplate collectCentRestTemplate(RestTemplateBuilder builder) {
return builder.rootUri("some uri")
.additionalInterceptors((ClientHttpRequestInterceptor) (request, body, execution) -> {
request.getHeaders().add("Authorization", "Bearer " + token);
return execution.execute(request, body);
}).build();
}
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization" , "Bearer token");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<(headers);
ResponseEntity<Object> response = null;
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("url");
try {
response = restTemplate.exchange(builder.toUriString(),
HttpMethod.GET,
entity, Object.class);
} catch (Exception e) {
e.printStackTrace();
}
You can try this one.
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