Fix 415 Unsupported Media Type Error in Spring Boot Quickly
Content-Type header matching the server's expected media type, and your controller method uses the proper @RequestBody annotation with supported media types like application/json.Why This Happens
This error occurs because the Spring Boot server expects a specific content type in the request body, but the client sends a different or missing Content-Type header. The server cannot find a suitable message converter to read the request data, so it rejects the request with a 415 status.
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @PostMapping("/users") public String createUser(String user) { return "User created: " + user; } }
The Fix
To fix the error, add the @RequestBody annotation to tell Spring Boot to parse the request body. Also, ensure the client sends the Content-Type: application/json header if JSON is expected. This allows Spring to use the correct message converter and process the data.
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @PostMapping("/users") public String createUser(@RequestBody String user) { return "User created: " + user; } }
Prevention
Always specify the expected content type in your controller methods using @RequestBody and validate client requests include the correct Content-Type header. Use tools like Postman or curl to test requests with proper headers. Additionally, configure your Spring Boot application to support common media types like JSON and XML by including the right dependencies.
Related Errors
- 400 Bad Request: Happens when request body is malformed or missing required fields.
- 406 Not Acceptable: Occurs when the server cannot produce a response matching the client's
Acceptheader. - 500 Internal Server Error: May happen if message converters fail unexpectedly.