Add Header Value For Spring TestRestTemplate Integration Test
Update: As of Spring Boot 1.4.0, TestRestTemplate
does not extend RestTemplate
anymore but still provides the same API as RestTemplate
.
TestRestTemplate
extends provides the same API as the RestTemplate
RestTemplate
, so you can use that same API for sending requests. For example:
HttpHeaders headers = new HttpHeaders();headers.add("your_header", "its_value");template.exchange(base, HttpMethod.GET, new HttpEntity<>(headers), Page.class);
If you want all of your requests using TestRestTemplate
to include certain headers, you could add the following to your setup:
testRestTemplate.getRestTemplate().setInterceptors( Collections.singletonList((request, body, execution) -> { request.getHeaders() .add("header-name", "value"); return execution.execute(request, body); }));
If you want to use multiple headers for all your requests, you can add the below
import org.apache.http.Header; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; private void setTestRestTemplateHeaders() { Header header = new BasicHeader("header", "value"); Header header2 = new BasicHeader("header2", "value2"); List<Header> headers = new ArrayList<Header>(); headers.add(header); headers.add(header2); CloseableHttpClient httpClient = HttpClients.custom().setDefaultHeaders(headers).build(); testRestTemplate.getRestTemplate().setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)); }
Once the headers are set you can either use TestRestTemplate [testRestTemplate]
or RestTemplate [testRestTemplate.getRestTemplate()]
for your REST calls