【问题标题】:Spring boot : How to make ContentType header purely optional? It throws a HttpMediaTypeNotSupportedException if not passedSpring boot:如何使 ContentType 标头完全可选?如果未通过,它会抛出 HttpMediaTypeNotSupportedException
【发布时间】:2021-04-02 17:33:35
【问题描述】:

即使没有传递 ContentType 标头,我也希望我的应用程序能够正常工作。就我而言,请求正文始终是 JSON。但是下面的代码总是抛出异常

org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型“application/x-www-form-urlencoded;charset=UTF-8”

public class UserController {
    @PostMapping(value = "/updateUser", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> updateUserDetails(@RequestBody User user) {
        //Do something
    }

这是意料之中的,但即使在创建自定义配置后,它也会给出相同的错误:

@Configuration
public class MyWebConfig implements WebMvcConfigurer {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON);
    }
}

如果我传递我想要使其成为纯可选的 ContentType 标头,这将正常工作。请帮忙。

【问题讨论】:

  • 你有没有尝试在你的配置类中添加注解@EnableWebMvc?
  • 您的控制器类是否标有@RestController 注解?
  • @Andrian:是的。它用 RestController 注释,我确实在配置中尝试了 EnableWebMvc 标记。不过运气不好。

标签: java spring spring-boot spring-mvc


【解决方案1】:

这个问题可能是因为User对象不能有任何getter/setter

【讨论】:

  • 它拥有所有的 getter 和 setter,包括一个无参数的构造函数。请注意,如果我传递内容类型标头,它工作正常。这意味着转换不是这里的问题。
猜你喜欢
  • 2023-03-12
  • 2020-11-28
  • 2020-03-13
  • 2017-08-10
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
  • 2023-04-02
  • 2020-10-28
相关资源
最近更新 更多