Spring return 自定义 Http 状态的最简单方法是什么,headers 和 body 到 Rest Client
Spring what is the easiest way to return custom Http status, headers and body to Rest Client
我想 return 给我的 Rest Client 最简单的答案。
只有:
- http状态码201
- http 状态消息已创建
- http header 内容 类型
- http 响应 body 自定义字符串答案
最简单的方法是什么?
我曾经这样使用ResponseEntity
object:
return new ResponseEntity<String>("Custom string answer", HttpStatus.CREATED);
,
但不幸的是,我不能简单地在构造函数中传递 http header。
我必须创建 HttpHeaders
object 并添加我的自定义 header,如下所示:
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);
但我正在寻找更简单的东西。可以适合一行代码的东西。
有人可以帮忙吗?
我想这会有所帮助:
@RequestMapping(value = "/createData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public String create(@RequestBody Object input)
{
return "custom string";
}
正如@M.Deinum 所建议的,这是最简单的方法:
@RequestMapping("someMapping")
@ResponseBody
public ResponseEntity<String> create() {
return ResponseEntity.status(HttpStatus.CREATED)
.contentType(MediaType.TEXT_PLAIN)
.body("Custom string answer");
}
我想 return 给我的 Rest Client 最简单的答案。 只有:
- http状态码201
- http 状态消息已创建
- http header 内容 类型
- http 响应 body 自定义字符串答案
最简单的方法是什么?
我曾经这样使用ResponseEntity
object:
return new ResponseEntity<String>("Custom string answer", HttpStatus.CREATED);
,
但不幸的是,我不能简单地在构造函数中传递 http header。
我必须创建 HttpHeaders
object 并添加我的自定义 header,如下所示:
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);
但我正在寻找更简单的东西。可以适合一行代码的东西。
有人可以帮忙吗?
我想这会有所帮助:
@RequestMapping(value = "/createData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public String create(@RequestBody Object input)
{
return "custom string";
}
正如@M.Deinum 所建议的,这是最简单的方法:
@RequestMapping("someMapping")
@ResponseBody
public ResponseEntity<String> create() {
return ResponseEntity.status(HttpStatus.CREATED)
.contentType(MediaType.TEXT_PLAIN)
.body("Custom string answer");
}