19
votes

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?

6
@RequestBody is for getting the full body and transform that into that object. However judging from your error you are simply posting a form then you should use @ModelAttribute instead, this is used for binding request parameters to objects.M. Deinum
can you post what are you posting to the webserviceRahul Singh
If you landed here trying to access the direct request-body input stream via @RequestBody InputStream, try InputStreamResource insteadJanaka Bandara

6 Answers

47
votes

In Postman. under Body, select raw and choose JSON from the drop down menu that appears. Then write the JSON that is the request body. You can't use form-data or x-www-form-urlencoded with @RequestBody, they are used when the binding is @ModelAttribute.

7
votes

The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation.

@RequestMapping(value = "/", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void createMessage(Message message){
        //TODO DO your stuff here
    }
4
votes

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);
    }
});
4
votes

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

4
votes

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

-1
votes

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";    }