Spring是将自定义Http状态,标头和正文返回给Rest Client的最简单方法 [英] Spring what is the easiest way to return custom Http status, headers and body to Rest Client
问题描述
我想向我的Rest Client返回最简单的答案. 只有:
I would like to return to my Rest Client the simplest answer. Only the:
- http状态码 201
- http状态消息已创建
- http标头内容类型
- http响应正文自定义字符串答案
- http status code 201
- http status message Created
- http header Content Type
- http response body Custom string answer
最简单的方法是什么?
我曾经以这种方式使用ResponseEntity
对象:
I've used to use ResponseEntity
object this way:
return new ResponseEntity<String>("Custom string answer", HttpStatus.CREATED);
,
但是不幸的是,我不能简单地在构造函数中传递http标头.
but unfortunately, I can not simple pass http header in constructor.
我必须创建HttpHeaders
对象,并在其中添加我的自定义标头,如下所示:
I have to create HttpHeaders
object and there add my custom header like this:
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);
但是我正在寻找更简单的方法.可能适合一行代码的东西.
But I am looking for something simpler. Something that could fit one line of code.
任何人都可以帮忙吗?
推荐答案
正如@ M.Deinum所建议的那样,这是最简单的方法:
As already suggested from @M.Deinum this is the easiest way:
@RequestMapping("someMapping")
@ResponseBody
public ResponseEntity<String> create() {
return ResponseEntity.status(HttpStatus.CREATED)
.contentType(MediaType.TEXT_PLAIN)
.body("Custom string answer");
}
这篇关于Spring是将自定义Http状态,标头和正文返回给Rest Client的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!