Keywords: Spring MVC | HttpMediaTypeNotSupportedException | Content-Type | @RequestBody | Media Type
Abstract: This article provides an in-depth analysis of the common HttpMediaTypeNotSupportedException in Spring MVC framework, focusing on the root causes of Content-Type mismatch issues. Through practical code examples, it explains the correct usage of @RequestBody annotation, configuration techniques for consumes attribute, and how to ensure media type consistency between client and server. The article offers complete solutions and best practice recommendations to help developers quickly identify and fix such problems.
Exception Phenomenon and Problem Analysis
During Spring MVC application development, developers often encounter the org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported exception. This exception typically occurs during HTTP request processing, indicating a mismatch between the client's Content-Type and the media type expected by the server.
From the provided code example, the issue primarily occurs in the PUT request handling method. The method uses the consumes = MediaType.APPLICATION_JSON annotation, indicating that it expects to receive data in JSON format. However, the client request header sets Content-Type as text/plain;charset=UTF-8, and this mismatch causes the exception.
Root Cause Analysis
When processing HTTP requests, the Spring MVC framework strictly checks whether the request's Content-Type header matches the consumes attribute defined in the controller method. When clients use tools like Simple Rest Template Google Extension to send requests, if the Content-Type header is not properly set, the tool may default to using text/plain as the Content-Type.
Another common issue is the choice of parameter binding method. In the original code, the @RequestParam annotation is used for parameter binding, which is typically suitable for query parameters or form data, not for JSON request bodies. For JSON format request bodies, the @RequestBody annotation should be used.
Complete Solution
To resolve this issue, modifications are needed at both the client and server levels. First, in the server-side controller, the @RequestBody annotation should be used to correctly bind the JSON request body:
@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody BudgetUpdateRequest request) throws GeneralException, ParseException {
// Processing logic
}Corresponding DTO classes also need to be defined to receive request data:
public class BudgetUpdateRequest {
private List<BudgetPerConsumerDTO> budgetPerDate;
// Getter and Setter methods
public List<BudgetPerConsumerDTO> getBudgetPerDate() {
return budgetPerDate;
}
public void setBudgetPerDate(List<BudgetPerConsumerDTO> budgetPerDate) {
this.budgetPerDate = budgetPerDate;
}
}Client Configuration Adjustment
When sending requests from the client, it is essential to ensure that the Content-Type header is correctly set to application/json. If using API testing tools like Postman, it needs to be explicitly set in the Headers tab:
Content-Type: application/jsonIf sending requests programmatically, the Content-Type also needs to be properly configured in the HTTP client:
// Example using Spring's RestTemplate
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<BudgetUpdateRequest> requestEntity = new HttpEntity<>(requestData, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class);Additional Considerations
Beyond the main Content-Type configuration issue, developers should also be aware of other situations that may cause similar exceptions. For example, when using Jackson annotations in entity classes, if there is a mismatch between @JsonManagedReference and @JsonBackReference annotations, it may also cause exceptions during serialization/deserialization.
Another common issue is character encoding settings. Although UTF-8 is the default encoding, in some special environments, inconsistent character encoding may also lead to media type processing failures.
Best Practice Recommendations
To avoid similar media type issues, developers are advised to follow these best practices: always explicitly specify consumes and produces attributes in controller methods; use dedicated DTO classes to receive request data instead of directly using business entities; carefully check Content-Type header settings before sending requests from the client; establish unified API specifications in team development to ensure media type consistency between frontend and backend.
Through the above analysis and solutions, developers can effectively avoid and handle HttpMediaTypeNotSupportedException exceptions, improving the stability and maintainability of Spring MVC applications.