【问题标题】:How can I get my spring boot controller to read the body of my http request to an object if the http request has content type urlencoded?如果http请求的内容类型为urlencoded,如何让我的spring boot控制器读取我的http请求的主体?
【发布时间】:2019-05-04 21:22:55
【问题描述】:

我是 spring 和 spring boot 的新手,并且已经设置了一个简单的控制器,如果存在将 content-type 设置为 application/json 的标头设置,它可以读取对对象的 http 请求。

但是,当我没有在标题中设置内容类型时,这不起作用并且我收到错误:"Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported"。我知道我从来没有告诉控制器我实际上希望它以 JSON 格式而不是 urlencoded 格式读取正文,我正在寻找一种方法。

我已经尝试过@RequestBody@RequestParam@ResponseBody 注释,但到目前为止都没有运气。

我还研究过通过设置默认和其他媒体类型来覆盖 WebMvcConfigurer.configureContentNegotiation 方法,但不太清楚我在这里做什么。

这是我当前形式的简单控制器

public class GreetingController {
    @RequestMapping(value = "/greeting",
            method = RequestMethod.POST)
    public Greeting postGreeting(@RequestBody Greeting body) {
        return new Greeting(body.getId(),"hello " + body.getContent());
    }
}

这是我的问候类的构造函数供参考:

public Greeting(long id, String content) {
    this.id = id;
    this.content = content;
}

我的请求正文是'{"id":10, "content": "world"}'

理想情况下,我想找到一种方法,能够将没有内容类型标头设置(因此可能默认为 form-urlencoded)的 http 请求处理为 JSON,以便在设置帖子时无需考虑请求并且控制器不那么脆弱。

【问题讨论】:

  • 如果那真的是你的请求体,那么它就是一个 JSON 体,内容类型应该是 application/json,而不是 application/x-www-form-urlencoded。使用正确的内容类型。为什么你用的不正确?
  • @JBNizet 的想法是控制器将能够同时处理 1) 如果 http 请求具有在标头中指定的内容类型或 2) 如果未指定。
  • 同意@JBNizet。内容类型有一个意义:使客户端和服务器之间的数据通信方式变得清晰。您尝试实现的内容:混乱/松散的内容类型既非标准又无意义。

标签: java spring spring-boot http


【解决方案1】:

试试这个:

    @RestController
    public class GreetingController {
    @RequestMapping(value = "/greeting",
            method = RequestMethod.POST)
    public HttpEntity<String> postGreeting(@RequestBody Greeting body) {
        //SETGREETING()
        return new HttpEntity<String>("data has been saved");
    }
}

别忘了接受 application/json 标头。

【讨论】:

    【解决方案2】:

    试试下面的代码 导入 org.springframework.web.bind.annotation.ModelAttribute;

      public class GreetingController {
          @RequestMapping(value = "/greeting",
                  method = RequestMethod.POST)
          public Greeting postGreeting(@ModelAttribute Greeting body) {
              return new Greeting(body.getId(),"hello " + body.getContent());
          }
      }
    

    【讨论】:

      猜你喜欢
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 2015-07-14
      • 2018-12-30
      • 2016-04-19
      • 1970-01-01
      相关资源
      最近更新 更多