I've just started using Spring, and I'm trying to receive a form-urlencoded POST body in a rest controller, but I can't for the life of me get it to work. Here's my "Hello World"-esque controller:
@RestController
public class MyController {
@ResponseBody
@RequestMapping(
value = "/",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE
)
public String index(@RequestBody String text) {
return "Text: " + text;
}
}
I've tried many different variations, all with differing errors. The particular configuration above produces the following error when receiving a POST request with a "text" parameter from Postman.
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.mywebsite.controllers.MyController.index(java.lang.String)
I've looked at many other stackoverflow posts about this topic and tried to implement their various solutions to no avail. Here's a list of the most promising ones:
There were a couple more that I can no longer find, and for most of these posts I've tried tweaking the annotations each time. I had great success when I tried GET and JSON POST requests, but for some reason these urlencoded requests refuse to work.
If you want to qet individual post parameters, just use RequestParam:
public String index(@RequestParam("text") String text) {
return "Text: " + text;
}
If you want to get several parameters at once, create a Command class, with JavaBean properties matching the parameters:
public class Command {
private String text;
private Integer number;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
}
and pass that as argument to your method:
public String index(Command command) {
return "Text: " + command.getText();
}
This is how I managed to solve the issue
@RequestMapping(value = "/test/", method = RequestMethod.POST, headers = {"content-type=application/x-www-form-urlencoded"})
public void waboxapp(WebRequest request) {
// then use something like:
log.debug("request payload: " + request.getParameter("data"));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.