Reputation: 4231
I am newbie using Spring . I am working on a code trying to pass headers using restTemplate.getForObject
client side :
String userServiceUrl = "http://localhost:8080/SampleRest/api/user/";
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", UUID.randomUUID().toString() );
restTemplate.getForObject(userServiceUrl + "{id}",User.class,HttpMethod.GET,headers) ;
however on server the request header "Authentication" is not passed at all . there is no header "Authentication"
requestHeaders.get("Authorization").get(0) //yields null exception
I cannot use restTemplate.exchange
what am I doing wrong ?
Help will greatly appreciated
Upvotes: 0
Views: 5517
Reputation: 9
We can use it in Spring boot for GET Method in the below manner :
@SpringBootApplication
public class Application implements CommandLineRunner{
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
try{
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders = this.createHeaders();
ResponseEntity<String> response;
response = restTemplate.exchange("<url>",HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
log.info(response.toString());
}
catch(Exception e)
{
System.out.println("Exception"+e);
}
}
private HttpHeaders createHeaders(){
HttpHeaders headers = new HttpHeaders(){
{
set( "Authorization", "3ee140");
}
};
return headers;
}
}
Upvotes: 0
Reputation: 8067
There is no option to pass headers in getForObject
method of restTemplate
.
You can implement ClientHttpRequestInterceptor
to set the headers if you don't want to use exchange
. You can also overwrite SimpleClientHttpRequestFactory
Upvotes: 1