我正在使用Spring Boot编写REST API。我的一个端点处理消耗JSON请求体的POST请求。同时,网址中提供了另一个参数。
@RequestMapping(
value = "/cycle?&visit={visitid}",
method = RequestMethod.POST,
consumes = "application/json",
produces = "text/plain")
@ResponseStatus(HttpStatus.CREATED)
public String persistCycleCount(@Valid @PathVariable Integer visitId, @Valid @RequestBody CycleCount cycleCount)
实体CycleCount
看起来像这样:
@实体
@Table(name =" CYCLE_CNT_HIST")
public class CycleCount implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "CYCLE_CNT_ID")
private long id;
@NotNull
@Column(name = "DOOR_ID")
private String activeDoorId;
@Column(name = "VISIT_ID")
private long visitId;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "SAMPLE_DTM")
private Date sampleDateTime;
@Column(name = "SAMPLE_TIMEZONE")
private int sampleTimeZone;
@NotNull
@Column(name = "SYS_CYCLE_CNT")
private int systemCycleCount;
@NotNull
@Column(name = "CTRLR_CYCLE_CNT")
private int controllerCycleCount;
当通过向/cycle?&visit=1
发送带有以下JSON的请求来测试api时,我得到了406。
{
"activeDoorId": "d002",
"controllerCycleCount": 15000,
"systemCycleCount": 78000
}
以下是请求的Swagger输出: 当我尝试通过在处理程序方法的第一行设置断点来调试时,它在发送请求后甚至没有命中该行。 我有其他端点类似于这个端点,它不需要在url中的变量,它们都工作。为什么我会得到406?
答案 0 :(得分:0)
1-也许你可以改变你的方法,你可以使用RequestParameter而不是PathVariable
2-为了验证RequestBody,您可以为验证数据添加BindingResult,并且可以显示您的请求是否有错误。
@RequestMapping(value = "/cycle",
method = RequestMethod.POST,
consumes = "application/json",
produces = "text/plain",
params = "visit")
@ResponseStatus(HttpStatus.CREATED)
public String persistCycleCount(@RequestParam("visitId") Integer visitId,
@Valid @RequestBody CycleCount cycleCount, BindingResult result){
if(result.hasErrors()){
// Handler request errors
}
// Body method
}