You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

POST请求向Spring(Jackson) REST控制器传String报415错误求助

解决Spring POST请求中415 Unsupported Media Type错误(字符串请求体场景)

问题描述

我最近尝试通过HTTP POST请求向Spring REST服务发送一个String对象,将该String放在请求体中,编写的控制器代码如下:

@RestController
@RequestMapping(value = "post", method = RequestMethod.POST)
public class HttpMethodPostController {
    /*HttpClientErrorException: 415 null*/
    @RequestMapping(value = "/string_as_text", consumes = MediaType.TEXT_PLAIN_VALUE)
    public ResponseEntity<Void> getStringAsText(@RequestBody String text) {
        System.out.println("[Server] text = ...");
    }
}

运行时遇到了HttpClientErrorException: 415 null错误,想请教解决方法。


问题原因与解决方案

415错误代表Unsupported Media Type,核心原因是服务器无法识别或处理请求携带的媒体类型。结合你的代码场景,给出以下针对性解决步骤:

1. 确保请求正确设置Content-Type头

这是最常见的触发原因:虽然你在控制器上指定了consumes = MediaType.TEXT_PLAIN_VALUE,但如果请求没有明确设置Content-Type: text/plain,Spring会默认尝试用application/json等格式解析请求体,与控制器的要求不匹配,从而抛出415错误。

举个请求示例:

  • 使用curl发送请求:
curl -X POST http://localhost:8080/post/string_as_text \
  -H "Content-Type: text/plain" \
  -d "需要发送的字符串内容"
  • 使用Postman等工具时,在Headers标签中添加Content-Type键,值设为text/plain,再在Body中输入字符串内容。

2. 检查并配置Spring消息转换器(可选)

如果已经正确设置请求头仍报错,可能是Spring上下文未注册处理纯文本的消息转换器(Spring Boot默认已包含,但手动配置Spring MVC时可能遗漏)。可以手动添加转换器确保支持text/plain:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 注册支持UTF-8编码的纯文本消息转换器
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }
}

3. 修复控制器方法的返回值(避免额外问题)

你的控制器方法声明返回ResponseEntity<Void>,但代码中没有返回语句,这会触发服务器内部错误。记得补充返回逻辑:

@RequestMapping(value = "/string_as_text", consumes = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<Void> getStringAsText(@RequestBody String text) {
    System.out.println("[Server] text = " + text);
    return ResponseEntity.ok().build();
}

内容的提问来源于stack exchange,提问作者user5132301

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:23:07