Spring Boot RestController类中出现content type 'text/plain;charset=UTF-8'不受支持的错误。

19

我有一个Spring Boot应用程序中的以下@RestController:

@Data
@RestController
public class Hello {

    @Autowired
    private ResturantExpensesRepo repo;

    @RequestMapping(value = "/expenses/restaurants",method = RequestMethod.POST,consumes =MediaType.APPLICATION_JSON_VALUE ,
            headers = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public void hello(@RequestBody ResturantExpenseDto dto)
    {
        Logger logger = LoggerFactory.getLogger("a");
        logger.info("got a request");

        ResturantExpenseEntity resturantExpenseEntity = new ResturantExpenseEntity();
        resturantExpenseEntity.setDate(new Date(System.currentTimeMillis()));
        resturantExpenseEntity.setName(dto.getName());
        resturantExpenseEntity.setExpense(dto.getExpense());
        repo.save(resturantExpenseEntity);
    }
}
当我尝试从restClient/RestedClient(都是mozila的插件)发送请求时,我遇到了以下错误:

{ "timestamp": 1512129442019, "status": 415, "error": "Unsupported Media Type", "message": "Content type 'text/plain;charset=UTF-8' not supported", "path": "/expenses/restaurants" }

这个错误表示终点不支持Json内容,但是我确实在 @RequestMapping 注释中加入了

consumes =MediaType.APPLICATION_JSON_VALUE

我错过了什么?


3
错误并没有说终端不支持JSON,而是它不支持text/plain。JSON的Content Type是application/json。在您的Mozilla插件中指定内容类型为application/json,问题就会得到解决。请注意保持原意,使语言通俗易懂,不要添加解释或其他额外内容。 - Yannic Bürgmann
@YannicKlem 我无法更改客户端以支持此Mediatype服务器端。 - jeevs
1
我知道,但你说的错误信息是端点不支持JSON。那是错误的。错误信息表明它不支持text/plain。因此,你在客户端发送的请求没有正确的Content-Type头。 - Yannic Bürgmann
请尝试像这样发出请求: curl -X PUT -H 'Content-Type: application/json' -i http://localhost:8080/spring-rest/api/employees/500 --data '{ "name": "abc", "email": "abc.a@gmail.com", "salary": 10000 }' - prashant.kr.mod
5个回答

24

虽然回复有点晚,但我遇到了同样的问题。也许对其他人有用的是,我安装了Postman,然后只需将Content-Type更改为application/json。


6
如果请求被这样发出:那么它将解决该问题。
curl -X PUT -H 'Content-Type: application/json' -i http://localhost:8080/spring-rest/api/employees/500 --data '{
  "name": "abc",
  "email": "abc.a@gmail.com",
  "salary": 10000
}'

我看到请求头是正确的:headers = MediaType.APPLICATION_JSON_VALUE
但当请求发送时,我们需要告知处理程序它是一个应用程序/JSON MIME类型。


1
这也有点晚了,但在RESTClient(Mozilla插件)中,您可以从标头下拉菜单添加Content-Type:application/JSON,并且甚至可以在响应侧将其更改为JSON格式。

0
如果您想通过Postman测试此API, - 转到Postman的Headers选项卡, - 点击Hidden headers(您将在顶部看到此信息) - 取消选中Content-Type - 添加新的头信息; Content-Type(键)和application/json(值) - 测试API,您将获得结果。

0
如果您正在使用带有Ajax的HTML,请检查请求头和有效载荷。确保Ajax具有以下字段。
                url : your url
                type : 'post',
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data : JSON.stringify( your payload )

如果 AJAX 调用具有以下字段,请删除它们并重试。
         processData : false,
         contentType : false,

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接