Spring RestTemplate to POST request with Custom Headers and a Request Object

MCF picture MCF · Feb 12, 2014 · Viewed 76.8k times · Source

In Spring RestTemplate is there a way to send Custom Headers together with a POST Request Object. I have already tried out the exchange method which is available. It seems that we can send key value pairs together with a custom headers but not a request object itself attached to the HttpEntity. The following code illustrates the attempt and it seems to be 400 BadRequest for the server.

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);

    HttpEntity<?> httpEntity = new HttpEntity<Object>(requestDTO, requestHeaders);

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.exchange(URL, HttpMethod.POST, httpEntity, SomeObject.class);

Anyone aware about this situation ? Or is it something which is not possible that Im trying to do ?

Answer

Andrew picture Andrew · Nov 12, 2014

Yes, It is possible, if use MultiValueMap headers instead of HttpHeaders

Example:

MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Authorization", "Basic " + base64Creds);
headers.add("Content-Type", "application/json");

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

HttpEntity<ObjectToPass> request = new HttpEntity<ObjectToPass>(objectToPassInstance, headers);

restTemplate.postForObject(urlPost, request, Boolean.class);

Boolean.class just because my controller returns boolean at this endpoint (could be anything)

Good luck with coding!