Search code examples
javaspringspring-bootresttemplate

Send custom headers RestTemplate


I am trying to set a custom header on my RestTemplate requests. I'm using Spring Boot 2.0.6.RELEASE

I try setting them like so, inside of my public method

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("muh Header", "muh value");

Every time I try and do this, it generates the following error

'HttpHeaders(java.util.Map<java.lang.String,java.util.List<java.lang.String>>)' has private access in 'java.net.http.

I understand the error message to mean that I'm trying to instantiate a private class outside of the class where the private class is declared.

So what is the best course of action?


Solution

  • I would go with something like this:

    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class WebController {
        private static final String template = "Hello, %s!";
    
        @RequestMapping("/greeting")
        public ResponseEntity<String> greeting(@RequestParam(value="name", defaultValue="World") String name){
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.add("thisiskey", "this is value");
            return new ResponseEntity<>(name, headers, HttpStatus.ACCEPTED);
        }
    }
    

    enter image description here

    Points to ponder :

    1. How often do you want to add a custom header and how often do they vary? If it is only applicable to one or two, you may consider this option however if it is more then twice i would suggest to use a http interceptor.

    2. header.add("","") -> which implements MultiValueMap does not accept a header.add("mua key", "...") -> as there is a space in the key.