jQuery Spring MVC 415 不支持的媒体类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18102452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:01:17  来源:igfitidea点击:

Spring MVC 415 Unsupported Media Type

jqueryajaxspringspring-mvc

提问by Hymanyesind

I am using Spring 3.2 and try to use an ajax post request to submit an array of json objects. If this is relevant, I escaped all special characters.

我正在使用 Spring 3.2 并尝试使用 ajax post 请求来提交一组 json 对象。如果这是相关的,我转义了所有特殊字符。

I am getting an HTTP Status of 415.

我得到 415 的 HTTP 状态。

My controller is:

我的控制器是:

@RequestMapping(value = "/save-profile", method = RequestMethod.POST,consumes="application/json")
    public @ResponseBody String saveProfileJson(@RequestBody String[] profileCheckedValues){
        System.out.println(profileCheckedValues.length);
        return "success";
    }

jquery is:

jquery是:

jQuery("#save").click(function () {
        var profileCheckedValues = [];
        jQuery.each(jQuery(".jsonCheck:checked"), function () {
            profileCheckedValues.push($(this).val());
        });
        if (profileCheckedValues.length != 0) {
            jQuery("body").addClass("loading");
            jQuery.ajax({
                type: "POST",
                contentType: "application/json",
                url: contextPath + "/sample/save-profile",
                data: "profileCheckedValues="+escape(profileCheckedValues),
                dataType: 'json',
                timeout: 600000,
                success: function (data) {
                    jQuery('body').removeClass("loading");
                },
                error: function (e) {
                    console.log("ERROR: ", e);
                    jQuery('body').removeClass("loading");
                }
            });
        }
    });

and an example of one of the objects from the array I am posting is the following json:

我发布的数组中的一个对象的示例是以下 json:

{
  "id": "534213341",
  "name": "Hyman Lindamood",
  "first_name": "Hyman",
  "last_name": "Lindamood",
  "link": "https://www.facebook.com/Hyman",
  "username": "Hyman",
  "gender": "male",
  "locale": "en_US",
  "updated_time": "2013-07-23T21:13:23+0000"
}

The error is:

错误是:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method

Why is this error happening - does anyone know?

为什么会发生此错误 - 有谁知道?

采纳答案by muthu

You may try with HttpServletRequest. it does not have any problem

您可以尝试使用HttpServletRequest. 它没有任何问题

  @RequestMapping(value = "/save-profile", method = RequestMethod.POST,consumes="application/json",headers = "content-type=application/x-www-form-urlencoded")
    public @ResponseBody String saveProfileJson(HttpServletRequest request){
       System.out.println(request.getParameter("profileCheckedValues"));
        return "success";
    }

回答by Swapneel

1) Add the following dependencies

1)添加以下依赖

<dependency>
    <groupId>com.fasterxml.Hymanson.core</groupId>
    <artifactId>Hymanson-core</artifactId>
    <version>${Hymanson-version}</version> // 2.4.3
</dependency>
<dependency>
    <groupId>com.fasterxml.Hymanson.core</groupId>
    <artifactId>Hymanson-databind</artifactId>
    <version>${Hymanson-version}</version> // 2.4.3
</dependency>

2) If you are using @RequestBody annotation in controller method make sure you have added following in xml file

2) 如果您在控制器方法中使用 @RequestBody 注释,请确保您已在 xml 文件中添加以下内容

<mvc:annotation-driven />

This should resolve the 415 status code issue.

这应该可以解决 415 状态代码问题。

回答by Bart

You will need to add Hymanson and Hymanson-databind to the classpath. Spring will pick it up using it's MappingHymansonHttpMessageConverter

您需要将 Hymanson 和 Hymanson-databind 添加到类路径中。Spring 会使用它来获取它MappingHymansonHttpMessageConverter

MappingHymansonHttpMessageConverter

MappingHymansonHttpMessageConverter

An HttpMessageConverter implementation that can read and write JSON using Hymanson's ObjectMapper. JSON mapping can be customized as needed through the use of Hymanson's provided annotations. When further control is needed, a custom ObjectMapper can be injected through the ObjectMapper property for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supports (application/json).

可以使用 Hymanson 的 ObjectMapper 读取和写入 JSON 的 HttpMessageConverter 实现。JSON 映射可以根据需要通过使用 Hymanson 提供的注释进行自定义。当需要进一步控制时,可以通过 ObjectMapper 属性注入自定义 ObjectMapper,用于需要为特定类型提供自定义 JSON 序列化器/反序列化器的情况。默认情况下,此转换器支持 (application/json)。

回答by Lucky

I had consume="application/json"in my request mapping configuration which expects a json input. When I sent a request which is not a JSON input Spring complained about the 415 Unsupported Media Type. So removing the consume="application/json"worked for me. So look into the request input and the accept media type in your Spring controller method signature. A mismatch would throw the 415 error. This will be most likely the reason for the issue.

consume="application/json"在我的请求映射配置中有一个需要 json 输入的配置。当我发送一个不是 JSON 输入的请求时,Spring 抱怨 415 Unsupported Media Type。所以删除consume="application/json"对我有用的。因此,请查看 Spring 控制器方法签名中的请求输入和接受媒体类型。不匹配会引发 415 错误。这很可能是问题的原因。

回答by Jitendra Tumulu

I had the same problem, I just brought up the below line of code in the spring-servlet.xml, it was at the almost end of this xml file. It worked. <mvc:annotation-driven />

我遇到了同样的问题,我只是在 spring-servlet.xml 中提出了以下代码行,它几乎在这个 xml 文件的末尾。有效。 <mvc:annotation-driven />

回答by Manoj Shrestha

I had the same problem. I had to follow these steps to resolve the issue:

我有同样的问题。我必须按照以下步骤解决问题:

1. Make sure you have the following dependencies:

1. 确保您有以下依赖项:

    <dependency>
        <groupId>com.fasterxml.Hymanson.core</groupId>
        <artifactId>Hymanson-core</artifactId>
        <version>${Hymanson-version}</version> // 2.4.3
    </dependency>
    <dependency>
        <groupId>com.fasterxml.Hymanson.core</groupId>
        <artifactId>Hymanson-databind</artifactId>
        <version>${Hymanson-version}</version> // 2.4.3
    </dependency>

2. Create the following filter:

2. 创建以下过滤器:

    public class CORSFilter extends OncePerRequestFilter {

        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {

            String origin = request.getHeader("origin");
            origin = (origin == null || origin.equals("")) ? "null" : origin;
            response.addHeader("Access-Control-Allow-Origin", origin);
            response.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, DELETE, OPTIONS");
            response.addHeader("Access-Control-Allow-Credentials", "true");
            response.addHeader("Access-Control-Allow-Headers",
                    "Authorization, origin, content-type, accept, x-requested-with");

            filterChain.doFilter(request, response);
        }
    }

3. Apply the above filter for the requests in web.xml

3. 对 web.xml 中的请求应用上述过滤器

    <filter>
        <filter-name>corsFilter</filter-name>
        <filter-class>com.your.package.CORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>corsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

I hope this is useful to somebody.

我希望这对某人有用。

回答by NimChimpsky

try changing jsonto application/jsonfor datatype. And what does your json look like is it valid? I have never seen json converted to a String[] before, so this coul dalso be the problem.

尝试改变json,以application/json用于数据类型。你的 json 看起来像什么是有效的?我以前从未见过 json 转换为 String[],所以这也可能是问题所在。