简体   繁体   English

Spring Rest 模板覆盖 Authorization 标头值

[英]Spring Rest template overwriting Authorization header value

I am making rest call like below:我正在拨打如下所示的休息电话:

REST_TEMPLATE.exchange(
        external_rest_url,
        HttpMethod.POST,
        new HttpEntity<>(dto, getHeaders()),
        Map.class)

and my headers are as below:我的标题如下:

private HttpHeaders getHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("User-Agent","Spring's RestTemplate");
    headers.set(HttpHeaders.AUTHORIZATION, "some value");
    return headers;
}

when I run my code the header HttpHeaders.AUTHORIZATION is getting replaced with undefined当我运行我的代码时,头HttpHeaders.AUTHORIZATION被替换为 undefined

See request header in snapshot below from network logs:从网络日志中查看下面快照中的请求标头: 在此处输入图片说明

Do anyone know why spring is behaving like this or specifically spring-web:5.0.5 jar.有谁知道为什么 spring 是这样的,或者特别是spring-web:5.0.5 jar。 I tried changing the version of jar as well but result is same.我也尝试更改 jar 的版本,但结果相同。

Springboot version I use is 2.0.x .我使用的 Springboot 版本是2.0.x

you can add an interceptor to your RestTemplate if you need to add the same headers to all requests:如果需要向所有请求添加相同的标头,则可以向 RestTemplate 添加拦截器:

public void sampleHeader(final RestTemplate restTemplate){
    //Add a ClientHttpRequestInterceptor to the RestTemplate
    restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor(){
        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
            request.getHeaders().set(HttpHeaders.AUTHORIZATION, "some value");//Set the header for each request
            return execution.execute(request, body);
        }
    }); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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