Spring what is the easiest way to return custom Http status, headers and body to Rest Client

江枫思渺然 提交于 2019-12-23 02:37:09

问题


I would like to return to my Rest Client the simplest answer. Only the:

  • http status code 201
  • http status message Created
  • http header Content Type
  • http response body Custom string answer

What is the easiest way?

I've used to use ResponseEntity object this way:

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

but unfortunately, I can not simple pass http header in constructor.

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.

Can Anyone help?


回答1:


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");
}



回答2:


I guess this will help:

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


来源:https://stackoverflow.com/questions/37677600/spring-what-is-the-easiest-way-to-return-custom-http-status-headers-and-body-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!