184

I am new to web programming in general, especially in Java, so I just learned what a header and body is.

I'm writing RESTful services using Spring MVC. I am able to create simple services with the @RequestMapping in my controllers. I need help understanding how to get HTTP header information from a request that comes to my method in my REST service controller. I would like to parse out the header and get some attributes from it.

Could you explain how I go about getting that information?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Horse Voice
  • 8,138
  • 15
  • 69
  • 120

4 Answers4

304

When you annotate a parameter with @RequestHeader, the parameter retrieves the header information. So you can just do something like this:

@RequestHeader("Accept")

to get the Accept header.

So from the documentation:

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                              @RequestHeader("Keep-Alive") long keepAlive)  {

}

The Accept-Encoding and Keep-Alive header values are provided in the encoding and keepAlive parameters respectively.

And no worries. We are all noobs with something.

Vidya
  • 29,932
  • 7
  • 42
  • 70
  • Thank you. In Some code examples in the company I work for, I see HttpServletRequest as the parameter and there is a getHeader method on it. Which approach is preferable? – Horse Voice Oct 24 '13 at 14:36
  • 1
    Prefer abstractions to the low-level details of an API. I would much rather have Spring MVC abstract away the details of the `Servlet` API. I can use the annotations to pull what I need out of the request. – Vidya Oct 24 '13 at 14:50
  • 7
    Should mention, you'll get a 400 bad request error as a response in case if request will not contain such header. More flexible way is direct access to request headers as described in: http://stackoverflow.com/a/28209710/1828296 – lospejos Jul 14 '16 at 13:43
  • I guess it depends on what you want to do, but a 400 response is the behavior I would almost always want in that case. – Vidya Nov 28 '16 at 17:41
  • 2
    @lospejos that can be avoided by using the ```required``` flag like `@RequestHeader(name = "Keep-Alive", required = false) long keepAlive` that will set the keepAlive to null if not provided. There is also `defaultValue` field for the annotation https://docs.spring.io/spring-framework/docs/5.0.7.RELEASE/javadoc-api/org/springframework/web/bind/annotation/RequestHeader.html – Niccolò Sep 18 '19 at 12:07
95

You can use the @RequestHeader annotation with HttpHeaders method parameter to gain access to all request headers:

@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
    // Use headers to get the information about all the request headers
    long contentLength = headers.getContentLength();
    // ...
    StreamSource source = new StreamSource(new StringReader(body));
    YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
    // ...
}
Paulo Merson
  • 13,270
  • 8
  • 79
  • 72
Debojit Saikia
  • 10,532
  • 3
  • 35
  • 46
  • What about the body of the http request? How do I access the header specifics? could you explain to me if HttpHeaders is a map that I need a key to access? – Horse Voice Oct 24 '13 at 16:33
  • HttpHeaders has getters to get the header specifics. you can explore this link to get the details: http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/http/HttpHeaders.html – Debojit Saikia Oct 24 '13 at 16:40
  • edited my answer to show how you can get access to the request body. – Debojit Saikia Oct 24 '13 at 16:46
  • 1
    Why is streamsource needed? It seems too complicated. There must be an easier way than to use streams etc. – Horse Voice Oct 25 '13 at 16:06
  • Here `StringReader` is used to read the incoming character stream. `StreamSource` works as a holder for a transformation source in the form of a stream of XML markup. – Debojit Saikia Oct 25 '13 at 16:11
  • Just what I was looking for. You can do a similar trick with request parameters: http://stackoverflow.com/questions/7312436/spring-mvc-how-to-get-all-request-params-in-a-map-in-spring-controller/18489124#18489124 – Rob Worsnop Dec 09 '15 at 21:46
18

My solution in Header parameters with example is user="test" is:

@RequestMapping(value = "/restURL")
  public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){

System.out.println(headers.get("user"));
}
Onic Team
  • 1,620
  • 5
  • 26
  • 37
Armando Cordova
  • 739
  • 7
  • 5
0

You can use HttpEntity to read both Body and Headers.

   @RequestMapping(value = "/restURL")
   public String serveRest(HttpEntity<String> httpEntity){
                MultiValueMap<String, String> headers = 
                httpEntity.getHeaders();
                Iterator<Map.Entry<String, List<String>>> s = 
                headers.entrySet().iterator();
                while(s.hasNext()) {
                    Map.Entry<String, List<String>> obj = s.next();
                    String key = obj.getKey();
                    List<String> value = obj.getValue();
                }
                
                String body = httpEntity.getBody();

    }
Sreepad Chitragar
  • 183
  • 1
  • 3
  • 12