masterdany88 masterdany88 - 3 years ago 177
reST (reStructuredText) Question

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

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
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
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?

Answer Source

As already suggested from @M.Deinum this is the easiest way:

public ResponseEntity<String> create() {
    return ResponseEntity.status(HttpStatus.CREATED)
       .body("Custom string answer");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download