Search code examples
javajsonspringspring-boothttprequest

How to get all HttpHeaders as a ResponseBody in Spring Boot?


I need to get the all HttpHeaders and then need to back all of these as a key-value pair as a ResponseBody. How can I achieve this?

@RestController
@RequestMapping("/employee")
public class Employee {

    @GetMapping
    public ResponseEntity<Object> hello(@RequestHeader HttpHeaders headers) {
        return ResponseEntity.ok().body(headers);
    }
}

Solution

  • Do this:

    @GetMapping
    public ResponseEntity<Object> hello(@RequestHeader HttpHeaders headers){
        return ResponseEntity.ok().body(headers.toSingleValueMap());
    }
    

    Though HttpHeaders is an implementation of Map, it is not well serialized into JSON. The method HttpHeaders#toSingleValueMap returns Map<String, String>.

    curl http://localhost:8080/employee --header 'foo: bar'
    
    {
      "foo": "bar",
    }