Spring boot Unsupported Media Type with @RequestBody

Viewed 91796

I checked in several different ways, also downloaded a new project to see what to check where is bug but I still do not know the answer.

That is my RestController

@RestController
@RequestMapping(value = "/message")
public class MessageController {

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public void createMessage(@RequestBody Message message){
        System.out.println(message);
    }
}

That is my Model

@Data
@Entity
public class Message {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String sender;
    private String telephone;
    private String message;
}

Gradle dependencies if necessary

dependencies {
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.0.pr3'
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-web')
    runtime('com.h2database:h2')
    runtime('org.postgresql:postgresql')
    compileOnly('org.projectlombok:lombok')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

and in postman i'm getting that error

{ "timestamp": 1495992553884, "status": 415, "error": "Unsupported Media Type", "exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
"message": "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported",
"path": "/message/" }

It is simplest way for rest but where I make a mistake?

8 Answers

You can write the code as
headers.put("Content-Type", Arrays.asList("application/json"));
instead of
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

You need a @NoArgsConstructor for the deserialization to work. If the no arguments constructor is not there, the Http message converters fail to map the json(other media type) to the Java object. And a 415 is returned

I had a similar issue using $.post Jquery. By adding correct contentType and dataType it worked for me.

$.ajax({
    type: "POST",
    url: "/api/design/save",
    data: JSON.stringify({
        id: floorId,
        shapes: shapes,
    }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
        console.log(data);
   },
    error: function(err) {
        console.log(err);
    }
});

What i did was to remove jackson libray and now I don't longer have that error, spent 2 days trying to figure out this, I hope this works for you!

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.11.3</version>
        <scope>test</scope>
    </dependency>

What I did:

  1. Set debug priority level in log4j.xml to 'debug'. Found HttpMediaTypeNotSupportedException.

  2. Put a debugger breakpoint in org.springframework.web.HttpMediaTypeNotSupportedException

  3. Realized that the incoming media type is text and the supported types are json and *json, although I used all - '*/*' in my annotation. Strange.

  4. Anyway, in my Angular application added headers:

    readonly headers = new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'}); this.http.post(url, JSON.stringify(this.model.value), {headers: this.headers})...

I got the same case with Json. Finally only this works Here code on react

export function setServices(jsonString) {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json;charset=UTF-8;");

var raw = jsonString;

var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: raw,
    redirect: 'follow'
};

fetch("http://localhost:8080/setservices", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));}

Code on controller

@RequestMapping(value = "/setservices", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody  String createMessage() throws Exception {
    //do smthg

    return "Ok";    }
Related