简体   繁体   中英

415 Unsupported Media Type - Spring version

I have this method on my controller:

@RequestMapping(value="/test", method = RequestMethod.POST)
public @ResponseBody String test(@RequestBody Test test) {
    return test.getName();
}

My Test class:

public class Test implements Serializable {

    private static final long serialVersionUID = -1150931681075770764L;

    private String name;
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
}

I post this json using:

{"name": "avocado"}

I also have this annotation:

<mvc:annotation-driven />

I'm using Advanced Rest Client to test it. My request's Content-Type is set to "application/json".

If I set spring version to 4.0.9.RELEASE or earlier I get 200 OK code when post.

If I set spring version to 4.1.0.RELEASE or later I get 415 Unsupported Media Type.

What shoud I do in order to get code 200 setting spring version to 4.2.1.RELEASE?

I suggest you to add

@RequestMapping(value="/test", method = RequestMethod.POST, 
    consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String test(@RequestBody Test test) {
    return test.getName();
}

Also conversion works with the HttpMessageConverter<?> to be able to serialize/deserialize in JSON format you need to have Jackson libraries in your classpath then spring will be able to instantiate the MappingJackson2HttpMessageConverter

Add this to your dependencies.

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson-json.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson-json.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson-json.version}</version>
        </dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM