2014-09-04 52 views
0

我是使用Spring的新手。我对代码的工作尝试使用restTemplate.getForObject没有通过RestTemplate.getForObject传递标头

客户端传递标题:

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

但是对服务器的请求头“认证”没有全部通过。没有标头 “身份验证”

requestHeaders.get("Authorization").get(0) //yields null exception 

我不能使用restTemplate.exchange

我究竟做错了什么?

帮助将不胜感激

+0

它应该不是requestHeaders.get(“Authentication”)。get(0)? – achingfingers 2014-09-04 14:28:38

+0

为什么?我用“授权”设置了一个标题,我希望在服务器端获得相同的标题 – igx 2014-09-04 14:52:33

回答

1

没有选项来传递报头中的restTemplategetForObject方法。

如果您不想使用exchange,则可以实施ClientHttpRequestInterceptor来设置标头。您也可以覆盖SimpleClientHttpRequestFactory

0

我们可以在下面的方式使用它在春季启动的GET方法:

@SpringBootApplication

公共类应用实现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; 
} 

}