[英]not getting headers passed with RestTemplate.getForObject
I am newbie using Spring . 我是使用Spring的新手。 I am working on a code trying to pass headers using restTemplate.getForObject 我正在尝试使用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 . 但是,在服务器上根本没有传递请求标头“ Authentication”。 there is no header "Authentication" 没有标题“ Authentication”
requestHeaders.get("Authorization").get(0) //yields null exception
I cannot use restTemplate.exchange 我不能使用restTemplate.exchange
what am I doing wrong ? 我究竟做错了什么 ?
Help will greatly appreciated 帮助将不胜感激
There is no option to pass headers in getForObject
method of restTemplate
. 没有选项传递头在getForObject
的方法restTemplate
。
You can implement ClientHttpRequestInterceptor
to set the headers if you don't want to use exchange
. 如果您不想使用exchange
则可以实现ClientHttpRequestInterceptor
来设置标头。 You can also overwrite SimpleClientHttpRequestFactory
您也可以覆盖SimpleClientHttpRequestFactory
We can use it in Spring boot for GET Method in the below manner : 我们可以通过以下方式在Spring Boot的GET方法中使用它:
@SpringBootApplication @SpringBootApplication
public class Application implements CommandLineRunner{ 公共类应用程序实现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;
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.