How to set an "Accept:" header on Spring RestTemplate request? How to set an "Accept:" header on Spring RestTemplate request? spring spring

How to set an "Accept:" header on Spring RestTemplate request?


I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders. (You can also specify the HTTP method you want to use.)

For example,

RestTemplate restTemplate = new RestTemplate();HttpHeaders headers = new HttpHeaders();headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));HttpEntity<String> entity = new HttpEntity<>("body", headers);restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

I prefer this solution because it's strongly typed, ie. exchange expects an HttpEntity.

However, you can also pass that HttpEntity as a request argument to postForObject.

HttpEntity<String> entity = new HttpEntity<>("body", headers);restTemplate.postForObject(url, entity, String.class); 

This is mentioned in the RestTemplate#postForObject Javadoc.

The request parameter can be a HttpEntity in order to add additionalHTTP headers to the request.


You could set an interceptor "ClientHttpRequestInterceptor" in your RestTemplate to avoid setting the header every time you send a request.

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);        }    }

Then

List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();interceptors.add(new HeaderRequestInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));RestTemplate restTemplate = new RestTemplate();restTemplate.setInterceptors(interceptors);


If, like me, you struggled to find an example that uses headers with basic authentication and the rest template exchange API, this is what I finally worked out...

private HttpHeaders createHttpHeaders(String user, String password){    String notEncoded = user + ":" + password;    String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());    HttpHeaders headers = new HttpHeaders();    headers.setContentType(MediaType.APPLICATION_JSON);    headers.add("Authorization", "Basic " + encodedAuth);    return headers;}private void doYourThing() {    String theUrl = "http://blah.blah.com:8080/rest/api/blah";    RestTemplate restTemplate = new RestTemplate();    try {        HttpHeaders headers = createHttpHeaders("fred","1234");        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);        ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);        System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());    }    catch (Exception eek) {        System.out.println("** Exception: "+ eek.getMessage());    }}