【问题标题】:Can not Send POST request to @RequestBody in Spring, error 415无法在 Spring 中向 @RequestBody 发送 POST 请求,错误 415
【发布时间】:2022-01-06 06:15:57
【问题描述】:

我目前正在做一个项目,我需要向 spring 发送一个 POST 请求。我已经寻找了几个小时的解决方案,但没有找到一个可以工作的解决方案。当我开发那部分时,这个请求奏效了。问题是,在创建一些新功能(另一个控制器中的 2 个新端点)之后,用于创建或更新实体的 POST 请求停止工作,而无需更改特定区域中的代码。

控制器:

@RestController
@CrossOrigin
@RequestMapping
public class SensorController {  

@PostMapping(value = "/createSensor", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<UUID> insertSensor(@RequestBody SensorDto sensorDto){
        UUID sensorId = sensorService.createSesor(sensorDto);
        return new ResponseEntity<>(sensorId,HttpStatus.CREATED);
    }
}

最初没有消耗和生产的部分,我尝试过是因为在其他帖子上看到但没有帮助。

SensorDto:

public class SensorDto extends RepresentationModel<SensorDto> {
private UUID id;
private String description;
private Integer maxValue;
private Device device;

来自邮递员的电话: image

标题:headers

有人可以帮我让它重新工作吗?

编辑:从另一个控制器询问的代码

@PostMapping("/addSensorToDevice")
public ResponseEntity<UUID> addSensor(@RequestBody DeviceSensorLinkDto deviceSensorLinkDto){
    System.out.println("OOO: " + deviceSensorLinkDto.toString());
    if(deviceService.addSensor(deviceSensorLinkDto)){
        return new ResponseEntity<>(deviceSensorLinkDto.getDeviceId(), HttpStatus.OK);
    }else {
        return new ResponseEntity<>(deviceSensorLinkDto.getDeviceId(), HttpStatus.EXPECTATION_FAILED);
    }
}

@PostMapping("/addClientToDevice")
public ResponseEntity<UUID> addClient(@RequestBody DeviceClientLinkDto deviceClientLinkDto){
    System.out.println("OOO: " + deviceClientLinkDto.toString());
    if(deviceService.addClient(deviceClientLinkDto)){
        return new ResponseEntity<>(deviceClientLinkDto.getDeviceId(), HttpStatus.OK);
    }else {
        return new ResponseEntity<>(deviceClientLinkDto.getDeviceId(), HttpStatus.EXPECTATION_FAILED);
    }
}

这个工作以及删除传感器实体的请求。

【问题讨论】:

  • 您可以尝试添加标题Accept: application/json。但是 UUID 不是有效的 JSON,所以你也可以尝试将 produces=APPLICATION_JSON_VALUE 替换为 TEXT_PLAIN_VALUE
  • 能否分享一下 SensorDto 构造函数?
  • @geobreze 我添加了标题但没有任何改变
  • @geobreze 尝试在邮递员中更改标头接受,它说 406 不接受,当我输入 TEXT_PLAIN_VALUE 时,如果我将其改回 JSON_VALUE 仍然给我 415
  • @mamunmohamed 我使用 Lombok 并且有 SensorDto 的 NoArgs 和 AllArgs 构造函数,但其​​他字段我将在稍后将实体保存到数据库之前设置

标签: java spring-boot post spring-restcontroller


【解决方案1】:

您的应用程序中似乎有多个 @JsonBackReference@JsonManagedReference,因此,您必须为所有对提供一个名称,如下所示:

@JsonBackReference(value = "something")

@JsonManagedReference(value = "something")
@JsonBackReference(value = "something-else")

@JsonManagedReference(value = "something-else")

您可以在reference documentation 中找到有关此的一些信息:

引用属性对的逻辑有;用于链接托管和 回参考。如果只有一个,则可以使用默认名称 引用对(例如,只有父/子的节点类 链接,由一个托管引用和匹配回组成 参考)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多