Sritam Jagadev
Sritam Jagadev

Reputation: 975

400 Bad request or 415 Unsupported Media type in Ajax post call

I have created a POST rest controller in spring. I want to call this controller from a ajax call.

@RequestMapping(value = "/getAdzAcrVehicle")
@RestController("AdzoneAcrVehicle")
public class AdzoneAcrVehicleController {

private static Logger LOG = Logger.getLogger(AdzoneAcrVehicleController.class.getName());

private String jsonresponse;
@Autowired
@Qualifier(value="AzoneAcrVehicleService")
private AzoneAcrVehicle azoneAcrVehicle;
@RequestMapping(method = RequestMethod.POST)
public String getAll(@RequestBody ObjectNode json) {
       System.out.println(json);
    return json.get("vehicle").asText();
}
}

I am trying to call that rest controller by using all below provided solutions, But I am getting 400 Bad request or 415 Unsupported Media type error.

1)

var parameter = JSON.stringify({vehicle:datas[3]});
                 $.ajax({
                        url: appName+'/getAdzAcrVehicle',
                        type: 'post',
                        dataType: 'json',
                        success: function (data) {
                           console.log(data);
                        },
                        data: parameter
                    });

2)

                 $.ajax({
                    type: 'post',
                    url: appName+'/getAdzAcrVehicle',
                    data: JSON.stringify(parameter),
                    contentType: "application/json; charset=utf-8",
                    traditional: true,
                    success: function (data) {
                    console.log(data);
                    }
                }); 

Upvotes: 0

Views: 1755

Answers (2)

shabinjo
shabinjo

Reputation: 1561

Since it is @RestController then @ResponseBody is not required. https://stackoverflow.com/a/25242458/6677551

You can specify the content type.

var parameter = JSON.stringify({vehicle:datas[3]});
    $.ajax({
            url: appName+'/getAdzAcrVehicle',
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json'
            success: function (data) {
                 console.log(data);
            },
            data: parameter
      });

Upvotes: 1

cralfaro
cralfaro

Reputation: 5948

You forgot the responseBody in your method

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String getAll(@RequestBody ObjectNode json) {
       System.out.println(json);
    return json.get("vehicle").asText();
}

Upvotes: 0

Related Questions