首页 > 解决方案 > 接收没有 Content-Type 标头的 RESTFUL 请求

问题描述

我正在练习弹簧靴并遇到问题。我有一个安静的 API 来接收来自其他 3rd 方的请求。我可以知道是否可以在没有 Content-Type 标头的情况下接收请求。由于没有 Content-Type=application/JSON 的请求,我一直面临错误 415-Unsupported Media Type。如果请求带有 ContentType 标头,问题就解决了。

    @RequestMapping(value = "backend", method = RequestMethod.POST)
public ResponseEntity<String> Backend(@RequestBody RequestDto RequestDto) throws NoSuchAlgorithmException {
    Service.process(RequestDto);
    return ResponseEntity.ok("OK");
}

这是我的其余 API 代码。感谢你的帮助。

标签: javaspring-boot

解决方案


感谢您的回复,并感谢所有试图帮助我的人。我从@daniu 发送的链接中找到了答案。Source :接收不带Content-Type header的请求 的解决方案 该解决方案不是使用springboot提供的@RequestBody,而是使用Gson手动将json字符串映射为object。

    @RequestMapping(value = "backend", method = RequestMethod.POST)
public ResponseEntity<String> Backend(HttpEntity<String> json) throws NoSuchAlgorithmException {
    ResponseDto ResponseDto = utils.gsonBuilder().fromJson(json.getBody(), ResponseDto.class);
    BackendService.process(ResponseDto);
    return ResponseEntity.ok("OK");
}

推荐阅读