Reputation: 23
Controller:
@RestController
public class ExampleCtrl {
@RequestMapping(name="/example", method=RequestMethod.POST)
public String example(@RequestBody String request) {
System.out.println("example: " + request);
return "OK";
}
}
And request (linux console):
curl -i -X POST 'https://localhost/example' -k -d 'name=value'
And spring console output:
example: name=value
But when I use @RequestBody Request request instead of @RequestBody String It doesn't work:
@RestController
public class ExampleCtrl {
@RequestMapping(name="/example", method=RequestMethod.POST)
public String example(@RequestBody Request request) {
System.out.println("example: " + request);
return "OK";
}
}
@JsonIgnoreProperties(ignoreUnknown=true)
class Request {
private String name;
public Request() {}
public String getName() {
return name;
}
}
I have exception:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
EDIT Resolved. It works when I use
curl -i -X POST 'https://localhost/example' -k -d '{"name": "value"}' --header "Content-Type:application/json"
Upvotes: 0
Views: 6404
Reputation: 7878
according to Spring documentation:
You convert the request body to the method argument by using an
HttpMessageConverter
.HttpMessageConverter
is responsible for converting from the HTTP request message to an object and converting from an object to the HTTP response body. TheRequestMappingHandlerAdapter
supports the@RequestBody
annotation with the following defaultHttpMessageConverters
:
ByteArrayHttpMessageConverter
converts byte arrays.
StringHttpMessageConverter
converts strings.
FormHttpMessageConverter
converts form data to/from a MultiValueMap.
SourceHttpMessageConverter
converts to/from a javax.xml.transform.Source.
so perhaps the request
argument is not a simple String (Specially you are using POST
) and couldn't be converted.
Upvotes: 1