lobs
lobs

Reputation: 439

Content type 'application/json;charset=UTF-8' not supported, when i try send JSON to Spring

When i send JSON package from jQuery to Spring RestController i have many errors:

In Spring:

Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported]

in Chrome:

POST http://localhost/post 415

(anonymous) @ main.js:11

My jQuery code:

$(document).ready(function() {

$('#go').on('click', function() {

    var user = {
        "name" : "Tom",
        "age" : 23
    };

    $.ajax({
        type: 'POST',
        url: "http://localhost/post",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(user),
        dataType: 'json',
        async: true
    });

   });

 });

My Spring RestController code:

@RestController
public class mainController {
@RequestMapping(value = "/post", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
        produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Object> postUser(@RequestBody User user){
System.out.println(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}

@RequestMapping(value = "/get", method = RequestMethod.GET)
public User getStr(){
    System.out.println("-------------------------");
    return new User("Tom", 56); //'Get' Check
}

}

Entity User:

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
  private String name;
  private int age;
}

Upvotes: 2

Views: 3936

Answers (1)

Vikas
Vikas

Reputation: 7165

you are using wrong mediatype i.e APPLICATION_FORM_URLENCODED_VALUE for consume in rest conttroller. Use MediaType.APPLICATION_JSON_UTF8_VALUE as you are passing json request.

@RestController
public class mainController {
@RequestMapping(value = "/post", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_JSON,
        produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Object> postUser(@RequestBody User user){
System.out.println(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}

@RequestMapping(value = "/get", method = RequestMethod.GET)
public User getStr(){
    System.out.println("-------------------------");
    return new User("Tom", 56); //'Get' Check
}

}

Upvotes: 1

Related Questions