HttpEntity 代表一个 HTTP request 或 response 由 headers 和 body 组成.
// Only talks about body & headers, but doesn't talk about status code
public HttpEntity(T body, MultiValueMap<String,String> headers)
ResponseEntity 扩展了 HttpEntity,但也添加了一个 Http 状态码。
// i.e ResponseEntity = HttpEntity + StatusCode
public ResponseEntity(T body, MultiValueMap<String,String> headers, HttpStatus statusCode)
因此用于完全 配置 HTTP 响应。
例如:
@ControllerAdvice
public class JavaWebExeptionHandler {
@Autowired
ExceptionErrorCodeMap exceptionErrorCodeMap;
@ExceptionHandler(RuntimeException.class)
public final ResponseEntity<ExceptionResponseBody> handleAllExceptions(Exception ex) {
Integer expCode = exceptionErrorCodeMap.getExpCode(ex.getClass());
// We have not added headers to response here, If you want you can add by using respective constructor
return new ResponseEntity<ExceptionResponseBody>(new ExceptionResponseBody(expCode, ex.getMessage()),
HttpStatus.valueOf(expCode));
}
}
@ResponseBody 表示使用它的 method 的 return 值绑定到响应 body
(意味着方法的返回值被视为Http响应体)