How to get access to HTTP header information in Spring MVC REST controller?

前端 未结 3 588
我在风中等你
我在风中等你 2020-11-30 23:41

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

相关标签:
3条回答
  • 2020-12-01 00:30

    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);
        // ...
    }
    
    0 讨论(0)
  • 2020-12-01 00:30

    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"));
    }
    
    0 讨论(0)
  • 2020-12-01 00:31

    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.

    0 讨论(0)
提交回复
热议问题