当你在 Spring Boot 应用中看到 Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported 错误时,通常意味着服务器期望接收的请求内容类型与客户端发送的不一致。通常在 RESTful API 场景下,服务器可能期望接收 application/json 或其他内容类型,但客户端发送了 application/x-www-form-urlencoded 类型的数据。
解决方案:
-
在客户端修改 Content-Type:
如果服务器期望接收其他类型(如application/json),你可以修改客户端请求的 Content-Type 为正确的类型。例如,使用
application/json:HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); -
修改 Spring Boot 控制器:
如果你希望服务器能够接收application/x-www-form-urlencoded类型的数据,可以在 Spring Boot 控制器中使用@RequestParam来处理表单数据,或者使用@RequestBody处理适当的媒体类型。使用
@RequestParam的例子:@PostMapping(value = "/endpoint", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public ResponseEntity<?> handleFormData(@RequestParam Map<String, String> formData) { // 处理表单数据 }使用
@RequestBody的例子:@PostMapping(value = "/endpoint", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public ResponseEntity<?> handleFormData(@RequestBody MultiValueMap<String, String> formData) { // 处理表单数据 } -
添加消息转换器:
如果你的控制器需要支持多种内容类型,包括application/x-www-form-urlencoded,确保你的 Spring Boot 应用配置了FormHttpMessageConverter。例如:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new FormHttpMessageConverter()); converters.add(new MappingJackson2HttpMessageConverter()); } }
根据具体的需求选择相应的解决方案。如果你需要处理 application/x-www-form-urlencoded 类型的数据,请相应调整服务器配置或客户端请求的内容类型。


8633

被折叠的 条评论
为什么被折叠?



