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

13,424

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

Solution 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";
}
Share:
13,424
masterdany88
Author by

masterdany88

Full-stack Java/Gwt Web Developer. Interested in software quality and software architecture. Always looking for new opportunities to learn something new and usefull. Main career goal: Software Architect position. Methodologies: Clean Code Design Patterns Java EE Architecture Agile JAVA: Design and implementation of Java EE based applications, using: PlayFramework2, Spring, GWT, JPA/ Hibernate, REST, SBT, Maven, Ant. WEB: Bootstrap, HTML5, JQuery. DB: MSSQL, MySql, H2DB. LINUX

Updated on June 05, 2022

Comments

  • masterdany88
    masterdany88 almost 2 years

    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?