Question

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 ?

Was it helpful?

Solution

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!

OTHER TIPS

  1. Try to enable full debug of Spring package. I'm sure you get more information about your "400 Bad Request":

    <logger name="org.springframework">
        <level value="DEBUG"/>
    </logger>
    
  2. Try to send same request with any rest tools (e.g. Rest Console Chrome plugin).

  3. See what happens on browser debug console ("Network" tab for Chrome, as example).

That steps always help me.

If you're using HttpClient 3.x, turn on logging by following this. If you're using HttpClient 4.x, turn on logging by following this. That should tell you what's getting sent across the wire, and be a decent starting point for debugging.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top