RestTemplate 统一添加 Header

一、添加拦截器

public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {

    private final String headerName;

    private final String headerValue;

    public HeaderRequestInterceptor(String headerName, String headerValue) {
        this.headerName = headerName;
        this.headerValue = headerValue;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        request.getHeaders().set(headerName, headerValue);
        return execution.execute(request, body);
    }
}

二、RestTemplate Bean

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new HeaderRequestInterceptor("token", "123"));

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(interceptors);

        return restTemplate;
    }
}

三、使用

@Autowired private RestTemplate restTemplate;
原文链接:https://www.cnblogs.com/victorbu/p/12708340.html
上一篇:【渝粤教育】国家开放大学2018年春季 0077-22T古代汉语专题 参考试题


下一篇:测试CSS代码