18

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 ?

MCF
  • 768
  • 2
  • 6
  • 21
  • 1
    Are you able to post the controller method that the above request is being made to? – Will Keeling Feb 12 '14 at 11:07
  • What's the header you are trying to send, "Content-Type"? Are you sure your server supports it? – Renan Ivo Feb 12 '14 at 15:26
  • @WillKeeling No, I was not able to make a successful request. It seems the request is not being properly created and the server replies 400 Bad Request. – MCF Feb 13 '14 at 05:58
  • @RenanIvo yeah. the server supports "Content-Type". – MCF Feb 13 '14 at 05:59

3 Answers3

74

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!

Andrew
  • 36,676
  • 11
  • 141
  • 113
  • @Andrey Rudenko how to receive this request and send response in server controller?? – KJEjava48 Feb 08 '16 at 05:32
  • @KJEjava48 1 - It is not about receiving a request, It is about posting data to a server with POST request to this server (for example after clicking "SUBMIT" button. – Andrew Feb 08 '16 at 07:07
  • @Andrey Rudenko i know that.I just like to know how its server side is working.You are passing an object like ObjectToPass and a token in header using HttpEntity in your request.So how should you retrieve these token and object in sever?I likes to use this method in my application so that i need to know about its server side also.That's why i am asking you this? – KJEjava48 Feb 08 '16 at 08:11
  • @KJEjava48 usually I'm getting the Token in a previous GET request (withing some JSON object). And then encode this Token with passw and uname to get "base64Creds" – Andrew Feb 08 '16 at 08:44
  • @Andrey Rudenko That's ok.But my question is how will you extract this "base64Creds" and "ObjectToPass" in the server when this request reaches your server? – KJEjava48 Feb 08 '16 at 08:56
  • @KJEjava48 You are not extracting base64Creds you're generating it (using for ex. https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/Base64Utils.html) from username:password:token – Andrew Feb 08 '16 at 10:12
  • @Andrey Rudenko Then what are you doing in ur server?.I need to pass a token and some data with the rest request.After seeing your answer i am planning to send my token in header and data in body of the restrequest.How will i do this?If its like above how can i retrieve these data in sever?? – KJEjava48 Feb 08 '16 at 10:26
  • >How will i do this? The Code is in the answer > how can i retrieve these data in sever? - I do not know, It depends on a server. – Andrew Feb 08 '16 at 13:22
  • @Andrey this helped me but why does new LinkedMultiValueMap() work and not HttpEntity? – tropikalista Sep 15 '17 at 13:47
  • I assume ObjectToPass is a custom object. I have a similar one but it is not resolving. This is the reason why I am getting a 400 Bad Request. My values are present in my custom object but it is not being retrieved in the postForObject method. Do I need to add some JSON annotations to my custom object? Thanks. – logixplayer Jan 10 '18 at 01:58
  • @ logixplayer I did some editing in one line HttpEntity request = new HttpEntity(objectToPassInstance, headers); Probably now it is less confusing. Yes - it is custom object (kinda POJO) – Andrew Jan 10 '18 at 11:54
  • For this to work in recent Spring Security environments you MUSTdisable CSRF-Protection like http.csrf().disable() – M46 Jul 23 '18 at 17:54
0
  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.

Vitalii Velikodnyi
  • 1,312
  • 11
  • 18
  • Only the first answer would apply here. 2 doesn't help because he'd have to recreate the request, which means he might change it, and 3 doesn't help because the client is Java. – Emerson Farrugia Mar 31 '14 at 13:07
  • 2
    This doesn't answer the question at all. He's not asking how to debug a 400 error. He's asking how to set custom headers in RestTemplate. – slim May 18 '15 at 14:03
  • Yes, but firstly you should to know reason of the BAD REQUEST to fix it or do you prefer guess? – Vitalii Velikodnyi Dec 11 '15 at 16:56
0

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.

Emerson Farrugia
  • 11,153
  • 5
  • 43
  • 51