Ger
Ger

Reputation: 649

PostMapping Service Rest with Spring boot error Request method 'POST' not supported

I'm not identifying the problem.

Controller

@RestController("/api")
public class CoordenadaController {

    @Autowired private RepositorioCoordenada repositorioCoordenada;

    @PostMapping("/salvar")
    public void save(String nome, int coordenadaX, int coordenadaY) {
        this.repositorioCoordenada.save(new Coordenada(nome, coordenadaX, coordenadaY));
        System.out.println("Salvou.....");
    }
}

PostMan Client

url localhost:8080/api/salvar?nome=Igreja&coordenadaX=10&coordenadaY=20

Log Erro PostMan Client

{
  "timestamp": 1493257315171,
  "status": 405,
  "error": "Method Not Allowed",
  "exception": "org.springframework.web.HttpRequestMethodNotSupportedException",
  "message": "Request method 'POST' not supported",
  "path": "/api/salvar"
}

Log Error Spring

Request method 'POST' not supported
2017-04-26 22:41:55.168  WARN 8388 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported

If you remove / api in @RestController the method annotated with @Post works

localhost:8080/salvar?nome=Igreja&coordenadaX=10&coordenadaY=20

Upvotes: 2

Views: 11193

Answers (2)

Jesus Castillo
Jesus Castillo

Reputation: 26

you need to set uri path on @RequestMapping after @RestController annotation, by example:

@RestController
@RequestMapping("/yourpath")
public class YourClass {
  ...
  ...
}

So, in your code you set this path in @RestController, that's the reason why postman request works on "/salvar" without /api path, because for spring this path wasn't declared.

Upvotes: 1

Elia Rohana
Elia Rohana

Reputation: 326

you are mixing POST with GET. if you want to do POST do the following:

@RestController("/api")
public class CoordenadaController {

@Autowired private RepositorioCoordenada repositorioCoordenada;

@PostMapping("/salvar")
public void save(@RequestBody Payload payload) {
    this.repositorioCoordenada.save(new Coordenada(payload.nome, payload.coordenadaX, payload.coordenadaY));
    System.out.println("Salvou.....");
}

}

public class Payload{
String nome, int coordenadaX, int coordenadaY

//getters & setters
}

then use the postmant accordingly: use post method, create a json payload and add it to the Body section

json payload:

{
    "nome": "bla bla",
    "coordenadaX": "1",
    "coordenadaY": "2"
}

you can check spring tutorial for for further information : https://spring.io/guides/gs/rest-service/

Upvotes: 1

Related Questions