常用的ResponseEntity.BodyBuilder和自定义ResponseEntity例子

ResponseEntity.ok() 和 ResponseEntity.BodyBuilder()
返回200(HttpStatus.SC_OK)

@RequestMapping("/check")
public ResponseEntity check() {
    BodyBuilder builder = (BodyBuilder) ResponseEntity.ok();
    builder.allow(HttpMethod.GET);
    builder.contentType(MediaType.TEXT_HTML);
    builder.eTag("W/MyeTag\"");
    return builder.body("Hello World!");
}

ResponseEntity.status()
使用HttpStatus返回需要的HttpCode

@RequestMapping("/handle")
public ResponseEntity handle() {
   return ResponseEntity.status(HttpStatus.SC_CREATED).body("Created Success");
}

ResponseEntity.created()
返回201(HttpStatus.SC_CREATED)

@RequestMapping("/handle")
public ResponseEntity handle() {
    URI location = null;
    try {
    location = new URI("http://www.concretepage.com/");
    } catch (URISyntaxException e) {
    e.printStackTrace();
    }
    return ResponseEntity.created(location).build();
} 

ResponseEntity.accepted()
返回202(HttpStatus.SC_ACCEPTED)

@RequestMapping("/handle")
public ResponseEntity handle() {
     return ResponseEntity.accepted().body("Hello World!");
} 

ResponseEntity.noContent()
返回204(HttpStatus.SC_NO_CONTENT)

@RequestMapping("/handle")
public ResponseEntity handle() {
    return ResponseEntity.noContent().build();
} 

ResponseEntity.badRequest()
返回400(HttpStatus.SC_BAD_REQUEST)

@RequestMapping("/handle")
public ResponseEntity handle() {
   return ResponseEntity.badRequest().body("Bad Request");
} 

ResponseEntity.notFound()
返回404(HttpStatus.SC_NOT_FOUND)

@RequestMapping("/handle")
public ResponseEntity handle() {
    return ResponseEntity.notFound().build();
} 

你可能感兴趣的:(Java)