内容类型“text/plain;charset=UTF-8”在RestController类中的spring boot中不支持错误

nad*_*gam 11 spring utf-8 spring-boot spring-web spring-restcontroller

我在 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试从 restClient/RestedClient(mozila 的两个插件)发送请求时,我收到以下错误:

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

这个错误指出终点不支持 Json 内容,但我确实把

消费 =MediaType.APPLICATION_JSON_VALUE

@RequestMapping注解内

我错过了什么?

Tar*_*rek 6

迟到的回应,但我在发布答案时遇到了同样的问题,它可能对某人有用,所以我安装了 Postman,然后将您的 Content-Type 更改为 application/json


pra*_*mod 5

如果请求是这样提出的:那么它将解决问题。

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
}'
Run Code Online (Sandbox Code Playgroud)

我看到标题是正确的: headers = MediaType.APPLICATION_JSON_VALUE
但是当发出请求时,那时我们需要通知处理程序它是 application/json mime 类型。