有没有见过这样的代码?
@PostMapping(value = "/sso/login", consumes = "application/json", produces = "application/json")public CommonResult<String> login() { /*省略代码*/ return CommonResult.success(true);}
这里的consumes和produces分别代表着这个接口可以消费什么样的请求类型和返回什么样的响应类型,然而,使用这种写法一来难看,二来如果容易写错而且调试起来会比较麻烦。这个时候我们通常会新建一个静态常量类来帮助我们管理这些请求头及相应头的相关静态常量配置。
然而,Spring框架已经帮你想到了这些,今天我们就来介绍下Spring框架帮我们提供的这些有用的封装帮助类~
org.springframework.http包
MediaType
MediaType类是一个媒体类型类,其官方注释为:
A subclass of MimeType that adds support for quality parameters as defined in the HTTP specification.
MimeType的子类,它为在HTTP标准中定义的能力参数提供了支持。
在MediaType类中封装了很多常见的文档类型:
public class MediaType extends MimeType implements Serializable { /*...*/ public static final String APPLICATION_FORM_URLENCODED_VALUE = "application/x-www-form-urlencoded"; public static final String APPLICATION_JSON_VALUE = "application/json"; public static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8"; public static final String APPLICATION_PDF_VALUE = "application/pdf"; public static final String APPLICATION_XML_VALUE = "application/xml"; public static final String IMAGE_JPEG_VALUE = "image/jpeg"; public static final String TEXT_HTML_VALUE = "text/html"; /*...*/}
在发送HTTP请求及相应HTTP请求时,经常会用到它们,比如发送时设置的HTTP Request的Accept字段与HTTP Response的Content-Type字段,那么之前的代码我们就可以这样:
@PostMapping(value = "/sso/login", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<Object> login() { /*...*/ return ResponseEntity.ok();}
基本常见的这些字段都封装在MediaType类中了。
HttpStatus
HttpStatus类是HTTP状态码包装类,其官方注释为:
Enumeration of HTTP status codes.
HTTP 状态码的枚举类
在HttpStatus中封装了很多常见的Http状态码:
public enum HttpStatus { /*...*/ OK(200, "OK"), MOVED_PERMANENTLY(301, "Moved Permanently"), FOUND(302, "Found"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401, "Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), METHOD_NOT_ALLOWED(405, "Method Not Allowed"), NOT_ACCEPTABLE(406, "Not Acceptable"), /*...*/}
经常性的,我们会在全局异常捕获里,增加对业务异常的处理,那么此时我们就可以用到这个类了:
@RestControllerAdvicepublic class GlobalException { @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseEntity<Object> exception() { /*...*/ return ResponseEntity.badRequest().build(); }}
像这样,我们可以用HttpStatus.BAD_REQUEST这个常量来处理未处理类型的异常,将相应状态码设置成400。
ResponseEntity
ResponseEntity是封装的一个HTTP响应实体封装类,其官方注释为:
Extension of HttpEntity that adds a HttpStatus status code. Used in RestTemplate as well @Controller methods.
继承HttpEntity类,添加了Http状态码的使用,通常用于RestTemplate的使用场景,同样也在@Controller注解的方法下使用。
官方注释还给出了一些示例:
In RestTemplate, this class is returned by getForEntity() and exchange(): ResponseEntity entity = template.getForEntity("http://example.com", String.class); String body = entity.getBody(); MediaType contentType = entity.getHeaders().getContentType(); HttpStatus statusCode = entity.getStatusCode();
Can also be used in Spring MVC, as the return value from a @Controller method: @RequestMapping("/handle") public ResponseEntity handle() { URI location = ...; HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setLocation(location); responseHeaders.set("MyResponseHeader", "MyValue"); return new ResponseEntity("Hello World", responseHeaders, HttpStatus.CREATED); }
Or, by using a builder accessible via static methods: @RequestMapping("/handle") public ResponseEntity handle() { URI location = ...; return ResponseEntity.created(location).header("MyResponseHeader", "MyValue").body("Hello World"); }
上面的示例很好看懂,即在RestTemplate场景、Spring MVC场景下的ResponseEntity类的使用。所以说,大家平时编程时点击阅读源代码的时候,下载其源代码并看注释是很有必要的。
HttpHeaders
HttpHeaders类是组装HTTP请求和响应头的类,同时也提供了了一些访问方法,其官方注释为:
A data structure representing HTTP request or response headers, mapping String header names to a list of String values, also offering accessors for common application-level data types.
一种数据结构,表示HTTP请求或响应头,将字符串头名称映射到字符串值列表,也为常见的公共应用级数据类型提供访问器。
其主要封装的常量及访问器如下:
public class HttpHeaders implements MultiValueMap<String, String>, Serializable { /*...*/ public static final String ACCEPT = "Accept"; public static final String ACCEPT_ENCODING = "Accept-Encoding"; public static final String ACCEPT_LANGUAGE = "Accept-Language"; ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials"; ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers"; public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";}
这个类的使用就比较广泛了,基本所有处理HTTP请求和响应的框架都在使用它,如Netty、Tomcat、OKHttp...,这里有必要说明下这个MultiValueMap类,因为我们的请求头经常性的一个Key对多个Value,如Accept字段有可能是application/json、application/xml,所以这个类是帮助我们处理这样特殊结构的泛型封装类。
常见的使用场景是如果我们需要从请求头里取某个值时,比如我们需要根据请求的UA来处理不同的浏览器请求:
@GetMapping("/detail")public ResponseEntity<Object> detail(@RequestHeader(HttpHeaders.USER_AGENT) String ua) { /*...*/ return ResponseEntity.ok().build();}
其它
该包下面还有很多其他的辅助类,如HttpCookie、CacheControl、HttpMethod等,因为使用方法比较简单,这里就不过多介绍了,感兴趣的可以直接在编程的过程中查看lib包后下载源代码查看~
网友评论