Reputation: 183
I have a problem with a Spring Boot REST controller - I'm trying to get it to serve both GET and HEAD methods at the same endpoint (as it theoretically should - supposedly, making a method respond to GET automatically enables HEAD as well).
The issue is that my GET method returns a response with body - something HEAD should never do. Thus, Spring hiccups when I try to HEAD into my endpoint and I'm all out of ideas why.
My controller method:
@RequestMapping(value = "/{ipAddress}", method = RequestMethod.GET)
public HttpEntity<ExitNode> getNode(@PathVariable("ipAddress") String ip) {
if (validateIp(ip)) {
if (!nodeCheckerService.checkNodeIp(ip)) {
return ResponseEntity.notFound().build();
} else {
return ResponseEntity.ok(nodeCheckerService.getNode(ip));
}
} else return ResponseEntity.badRequest().build();
}
Everything works fine when I HEAD into the endpoint with a malformed parameter, I get 400 Bad Request and everything's fine. The only problem is with the scenario in which GET returns a body and HEAD should not.
EDIT:
It turned out that Postman was the problem - it didn't parse the response correctly. Installing Insomnia and checking the endpoint proved that the code is OK.
Upvotes: 1
Views: 2325
Reputation: 1148
Enable your logging to show you the mappings. With mine enabled I see the follwing;
To enable logging add logging.level.org.springframework.web=TRACE
to your application.properties
My Restful endpoint.
@RestController
@RequestMapping("/user")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@RequestMapping(value = "/{userId}", method = {RequestMethod.GET, RequestMethod.HEAD})
public ResponseEntity<User> user(@PathVariable("userId") String userId) {
return ResponseEntity.ok(this.userService.getUser(userId));
}
}
See postman screenshots below showing success when doing a GET or HEAD to the same endpoint and with same @PathVariable
Get request with response body:
HEAD request with no response body:
Upvotes: 1