RestTemplate 에 Custom header 추가하기

By | 2020년 11월 15일
Table of Contents

RestTemplate 에 Custom header 추가하기

생성자를 이용한 RestTemplate 생성

생성자에서 RestTemplate 을 생성하면 매번 인증관련 정보를 추가하지 않고 한번의 설정으로 header 를 추가할 수 있다.

@Controller
public class MenuIndexController {

    final String TARGET_URI = "http://localhost:8081/v1/settings/menu";

    private final RestTemplate restTemplate;

    @Autowired
    public MenuIndexController(RestTemplateBuilder builder) {

        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new HeaderRequestInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));
        interceptors.add(new HeaderRequestInterceptor("ContentType", MediaType.APPLICATION_JSON_VALUE));
        interceptors.add(new HeaderRequestInterceptor("HTTP_AUTH_ACCESS_ID", "skyer9"));
        interceptors.add(new HeaderRequestInterceptor("HTTP_AUTH_ACCESS_KEY", "12345678"));

        this.restTemplate = builder
                .setConnectTimeout(Duration.ofMillis(3000))
                .setReadTimeout(Duration.ofMillis(3000))
                .additionalInterceptors(interceptors)
                .build();
    }
    // ......
}

답글 남기기