Spring 什么是将自定义 Http 状态、标头和正文返回到 Rest Client 的最简单方法



我想回到我的 Rest 客户端最简单的答案。只有:

  • HTTP 状态代码 201
  • http 状态消息已创建
  • http 标头内容类型
  • http 响应正文 自定义字符串答案

最简单的方法是什么?

我曾经这样使用ResponseEntity对象:

return new ResponseEntity<String>("Custom string answer", HttpStatus.CREATED);

但不幸的是,我不能简单地在构造函数中传递 http 标头。

我必须创建HttpHeaders对象,并在那里添加我的自定义标头,如下所示:

MultiValueMap<String, String> headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
return new ResponseEntity<String>("Custom string answer", headers, HttpStatus.CREATED);

但我正在寻找更简单的东西。可以容纳一行代码的东西。

谁能帮忙?

正如 @M.Deinum 所建议的那样,这是最简单的方法:

@RequestMapping("someMapping")
@ResponseBody
public ResponseEntity<String> create() {
    return ResponseEntity.status(HttpStatus.CREATED)
       .contentType(MediaType.TEXT_PLAIN)
       .body("Custom string answer");
}

我想这会有所帮助:

@RequestMapping(value = "/createData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public String create(@RequestBody Object input)
{
    return "custom string";
}

最新更新