如何使用spring ResponseEntity处理http响应呢?
下文笔者讲述ResponseEntity处理http响应的简介说明,如下所示
ResponseEntity简介
ResponseEntity可以理解为一个包装类 它将Http内容包装为: 状态码、头部信息以及相应体内容
ResponseEntity示例分享
@GetMapping("/hello")
ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello java265.com", HttpStatus.OK);
}
可以通过编程方式指明响应状态,所以根据不同场景返回不同状态:
@GetMapping("/test")
ResponseEntity<String> age(
@RequestParam("test") int test) {
if (isInFuture(test)) {
return new ResponseEntity<>(
"error info ",
HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(
"ok " + calculateAge(test),
HttpStatus.OK);
}
----设置http响应头
@GetMapping("/testHeader")
ResponseEntity<String> testHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "test");
return new ResponseEntity<>(
"信息头为:", headers, HttpStatus.OK);
}
链式编程的ResponseEntity编写
@GetMapping("/test")
ResponseEntity<String> test() {
return ResponseEntity.ok()
.header("Custom-Header", "头信息")
.body("这里设置了头信息");
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


