简体   繁体   中英

not getting headers passed with RestTemplate.getForObject

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

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

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;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM