我有一个Spring端点,如下所示:
@PostMapping(path = "/test",
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseStatus(HttpStatus.OK)
public TestDTO test(TestDTO testDTO){
return testDTO;
}
DTO如下所示:
public class TestDTO {
@ApiModelProperty(
name = "sample",
value = "sample",
dataType = "String",
example = "shhhhhh"
)
private String sample;
}
很明显,curl请求如下所示:
curl --location --request POST 'localhost:8081/test' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'sample=testReturnData'
退货
{
"sample": "testReturnData"
}
但是如果我加一个这样的参数
curl --location --request POST 'localhost:8081/test?sample=doNotIncludeThis' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'sample=testReturnData'
我得到的回复是这样的:
{
"sample": "doNotIncludeThis,testReturnData"
}
我只想让spring从body中获取数据,而不是param。
{
"sample": "testReturnData"
}
@RequestBody
注解不适用于x-www-form-url-encoded
(这是我需要的格式),因为它将返回一个415。
1条答案
按热度按时间hof1towb1#
我认为你在寻找错误的解决方案。为什么你在使用
@RequestBody
的时候会得到一个415?这不是标准行为。您可以看到,当使用
application/x-www-form-urlencoded
时,Spring无法识别请求的主体。spring-web模块提供了FormContentFilter来拦截内容类型为application/x-www-form-urlencoded的HTTP PUT、PATCH和DELETE请求,从请求主体读取表单数据,并 Package ServletRequest以使表单数据通过ServletRequest. getParameter *()方法家族可用。
为了正确地配置Spring,您需要配置Spring的
FormContentFilter
,这应该是默认启用的,但是您可以通过在application.properties
中设置它来确保它是启用的。