【问题标题】:Multiple Content-type in Spring MVCSpring MVC 中的多种内容类型
【发布时间】:2018-08-05 16:17:58
【问题描述】:

我们可以在 Spring MVC 请求标头中有多个内容类型吗? 我路过:

{Content-type = application/json, text/plain}

通过 Postman 到我的 API。目前,我收到org.springframework.web.HttpMediaTypeNotSupportedException: Invalid mime type ....

我想知道,我的输入值是否有问题,或者我们的标题中不能有多个内容类型。

Controller:

@RequestMapping(value = "/addressees", 产生 = APPLICATION_JSON_UTF8_VALUE, 方法 = GET)

【问题讨论】:

    标签: spring rest api spring-mvc mime-types


    【解决方案1】:

    是的,spring mvc 请求映射支持多种消费 MIME 类型,示例如下

    @RequestMapping(value = "/something", method = PUT, 
                    consumes = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE}, 
                    produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE})
    public SomeObject updateSomeObject(SomeObject acct) {
        return doStuff(acct);
    }

    在请求映射中添加消耗部分,例如 - consumes = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE}

    想了解更多,请参考此链接 -

    https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html

    【讨论】:

      【解决方案2】:

      每个请求的请求标头可以有一种内容类型。您向服务器指定实际发送的数据类型。

      您的服务器/API 端点可以支持多个。

      所以如果你的请求同时指定了application/json和text/plain,我相信是你的请求有问题。

      【讨论】:

        【解决方案3】:

        是的,RequestMapping.consumes 接受 Mime 类型数组

        String[] consumes() default {};

        请注意,您必须使用consumes 来定义传入的 MIME 类型。 produces 用于传出类型。

        【讨论】:

          猜你喜欢
          • 2011-05-23
          • 2011-05-23
          • 2014-06-08
          • 2012-08-13
          • 2014-10-21
          • 2014-11-15
          • 2018-10-18
          • 2019-06-27
          • 1970-01-01
          相关资源
          最近更新 更多