3

我有一个 Spring RestController,当我GET从中获取数据时效果很好,但是当我尝试PUT使用相同的数据时,我得到一个400 Bad Request.

这是我的控制器的最简单版本,它仍然可以工作(我省略了GET方法):

@RestController
@RequestMapping("/configuration/ledstrips/{name}/display")
public class DisplayController {

    @ResponseBody
    @RequestMapping(method = RequestMethod.PUT, produces = { "application/hal+json" })
    public DisplayResource setDisplay(@PathVariable String name, @RequestBody DisplayResource display) {

        return display;
    }
}

这是DisplayResource

public class DisplayResource extends ResourceSupport {

    private List<Color> pixels;

    public List<Color> getPixels() {

        return pixels;
    }


    public void setPixels(List<Color> pixels) {

        this.pixels = pixels;
    }
}

我几乎从另一个分支复制了这段代码,它在那里工作!

我想不通!

编辑

这是GET-方法:

@ResponseBody
@RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json" })
public DisplayResource getDisplay(@PathVariable String name) {

    LEDStripDTO ledStripDTO;

    try {
        ledStripDTO = ledStripDTOService.getDTO(name);
    } catch (IOException | NullPointerException exception) {
        throw new LoadFailedException("Error loading LED strip:", exception);
    }

    Link self = linkTo(methodOn(DisplayController.class).getDisplay(name)).withSelfRel();

    DisplayResource displayResource = new DisplayResource();

    displayResource.add(self);

    try {
        displayResource.setPixels(ledStripService.getPixels(ledStripDTO));
    } catch (IOException | TimeoutException | AlreadyConnectedException | NotConnectedException exception) {
        throw new LoadFailedException("Error getting Information from LED strip:", exception);
    }

    return displayResource;
}

它产生的结果(对于长度为 1 的 LED 灯条):

{
  "pixels": [
    {
      "red": 0,
      "green": 16,
      "blue": 0
    }
  ],
  "_links": {
    "self": {
      "href": "http://localhost:8080/configuration/ledstrips/devled/display"
    }
  }
}

当我发送这个时,无论是否有_links段,我都会收到400错误消息。

4

1 回答 1

3

因为它是 a PUT,所以您定义了 aproduces但不是 a consumes。可能是端点不知道期望正文采用什么格式,这就是它拒绝它的原因。尝试:

查看您提供的源代码后,我可以看到Color该类有一个需要参数的构造函数。由于此构造函数,Jackson 库提供的默认值ObjectMapper将无法解组 JSON 字符串。尝试Color在当前类旁边添加一个默认构造函数:

public Color(int red, int green, int blue) {

    this.red = setColorLimits(red);
    this.green = setColorLimits(green);
    this.blue = setColorLimits(blue);
}

public Color() {}
于 2015-07-17T13:45:28.237 回答