Spring Boot接口接收Integer类型@RequestBody参数时Postman请求400错误排查
Spring Boot接口Postman请求400错误原因及解决方案
错误原因
你在Postman中传入raw文本类型的数字1时,请求头的Content-Type默认是text/plain。而Spring Boot的默认配置里,没有对应的消息转换器能把text/plain格式的文本直接转换成Integer类型,因此无法解析请求体,返回400 Bad Request错误。如果把参数改成String,StringHttpMessageConverter可以处理text/plain类型,所以不会报错。
解决方案
方案一:调整Postman请求配置(无需修改代码)
- 方式1:在Postman的Body区域选择
raw后,将右侧的格式从Text切换为JSON,直接传入数字1(无需加引号),此时请求头的Content-Type会自动设为application/json,Spring Boot的JSON转换器能正常将该数值解析为Integer。 - 方式2:保持
Text格式,手动在请求头中添加Content-Type: application/json,请求体传入数字1,同样能被JSON转换器解析。
方案二:添加自定义消息转换器(无需修改请求)
如果不想调整Postman的请求方式,可以在Spring Boot项目中添加自定义消息转换器,支持将text/plain类型的文本转换为Integer。示例代码如下:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new HttpMessageConverter<Integer>() { @Override public boolean canRead(Class<?> clazz, MediaType mediaType) { return clazz == Integer.class && MediaType.TEXT_PLAIN.equals(mediaType); } @Override public boolean canWrite(Class<?> clazz, MediaType mediaType) { return false; } @Override public List<MediaType> getSupportedMediaTypes() { return Collections.singletonList(MediaType.TEXT_PLAIN); } @Override public Integer read(Class<? extends Integer> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { String body = StreamUtils.copyToString(inputMessage.getBody(), StandardCharsets.UTF_8); try { return Integer.parseInt(body.trim()); } catch (NumberFormatException e) { throw new HttpMessageNotReadableException("无法将文本转换为整数类型", e, inputMessage); } } @Override public void write(Integer integer, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { // 无需实现写逻辑 } }); } }
内容的提问来源于stack exchange,提问作者Mehdi Rahimi
相关产品推荐
相关产品推荐

