2017-10-11 94 views
0

我正在使用Spring Boot編寫REST API。我的一個端點處理POST請求,該請求使用JSON請求主體。同時,另一個參數在URL中提供。爲什麼406發送包含路徑變量和請求正文的請求

@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看起來是這樣的: @Entity @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; 

當測試通過發送請求具有以下JSON到/cycle?&visit=1的API,我得到了406 。

{ 
    "activeDoorId": "d002", 
    "controllerCycleCount": 15000, 
    "systemCycleCount": 78000 
} 

這裏是請求的揚鞭輸出: enter image description here 當我嘗試通過在處理程序方法的第一行設置斷點來進行調試時,它在發送請求後甚至沒有命中該行。 我有其他的終端類似於這個不需要在url中的變量,他們都工作。我爲什麼得到406?

回答

0

1 - 也許你可以改變你的方法,你可以使用不PathVariable一個RequestParameter

2-爲了驗證你可以把一個BindingResult用於驗證數據的RequestBody,並可以顯示,如果你的申請有錯誤。

@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 
} 
+0

使用'RequestParam'工作。當你已經有@ Valid語句來驗證JSON時,你需要什麼'BindingResult'? – ddd

相關問題