Search code examples
spring-bootpostmanspring-restcontroller

Why does not the post method work when the Get method works in RestController?


My GET method is working fine with Json but I always get an error when I used post method. I used codes that in below.

RestController

@RestController
@RequestMapping("/api")
public class AjaxApiRestController {

    private static final String[] province = {
            "Aragon",
            "Catalonia"
    };

    private static final String[][] district =  {
            {"Barbastro","Fraga","Jaca"},
            {"Granollers","Vich","Barcelona"}
    };

    @GetMapping("/ajax/district") //it working!
    public List<String> getDistrict(@RequestBody Province province){
        for(int i=0; i<this.province.length; i++){
            if(this.province[i].equals(province.getProvince())){
                return Arrays.asList(district[i]);
            }
        }
        return null;
    }

    @PostMapping("/ajax/district") //it's not working!
    public List<String> getDistrictPost(@RequestBody Province province){
        for(int i=0; i<this.province.length; i++){
            if(this.province[i].equals(province.getProvince())){
                return Arrays.asList(district[i]);
            }
        }
        return null;
    }
}

Province

class Province{

    private String province;

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }
}

I use Postman to check the RestController.

In GET method: By sending this command I get the following output.

{
    "province":"Catalonia"
}

GET output:

[
    "Granollers",
    "Vich",
    "Barcelona"
]

In POST method: By sending this command I get the following output.

{
    "province":"Catalonia"
}

POST output:

{
"timestamp": "2019-02-25T08:52:10.850+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/api/ajax/district"
}

As a result, when we examine the codes, the GET method works and the POST method does not work. Why does not the post method work when the Get method works? Is there error in code that I can't see? Is there anyone who can help?


Solution

  • Why you are trying to use both (POST, GET) Methods for the same functionality. using @RequestBody with a GET method is not a good practice. Have you added spring security dependency and configuration?

    If yes, then adding method name may help you as below. .antMatchers(HttpMethod.POST,"/yourRequestURL").permitAll()