185

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?

4 Answers 4

306

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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?
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.
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: stackoverflow.com/a/28209710/1828296
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.
@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 docs.spring.io/spring-framework/docs/5.0.7.RELEASE/javadoc-api/…
96

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);
    // ...
}

6 Comments

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?
HttpHeaders has getters to get the header specifics. you can explore this link to get the details: docs.spring.io/spring/docs/3.1.x/javadoc-api/org/…
edited my answer to show how you can get access to the request body.
Why is streamsource needed? It seems too complicated. There must be an easier way than to use streams etc.
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.
|
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"));
}

Comments

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();

    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.