Spring居然还提供了这么好用的URL工具类

1. 前言
开发中我们经常会操作 URL,比如提取端口、提取路径以及最常用的提取参数等等。很多时候需要借助于一些第三方类库或者自己编写工具类来实现,今天胖哥给大家介绍一种方法,无需新的类库引入,只要你使用了 Spring Web 模块都可以轻松来完成对 URL 的组装和分解提取。
2. UriComponents
JDK 虽然提供了
java.net.URI
,但是终归还是不够强大,所以 Spring 封装了一个不可变量的 URI 表示
org.springframework.web.util.UriComponents
。
UriComponentsBuilder
我们可以利用其构造类
UriComponentsBuilder
从
URI
、Http 链接、URI 路径中初始化
UriComponents
。以 Http 链接为例:
String httpUrl= "https://felord.cn/spring-security/{article}?version=1×tamp=123123325";
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(httpUrl).build();
如果不是 Http 就不能使用上面的方法了,需要使用
fromUriString(String uri)
。
我们也可以直接构造一个
UriComponents
:
UriComponents https = UriComponentsBuilder.newInstance()
.scheme("https")
.host("www.felord.cn")
.port("8080")
.path("/spring-boot/{article}")
.queryParam("version","9527")
.encode(StandardCharsets.UTF_8)
.build();
// https://www.felord.cn:8080/spring-boot/{article}?version=9527
3. 操作 UriComponents
提取协议头
如果想提取协议头,如上面的例子我们想提取
https
。
String scheme = uriComponents.getScheme();
// scheme = https
System.out.println("scheme = " + scheme);
提取 Host
获取
host
也是很常见的操作。
String host = uriComponents.getHost();
// host = felord.cn
System.out.println("host = " + host);
提取 Port
获取 uri 的端口。
int port = uriComponents.getPort();
// port = -1
System.out.println("port = " + port);
但是很奇怪的是上面的是
-1
,很多人误以为会是80
。其实 Http 协议确实是80
,但是java.net.URL#getPort()
规定,若 URL 的实例未申明(省略)端口号,则返回值为-1
。所以当返回了-1
就等同于80
,但是 URL 中不直接体现它们。
提取 Path
提取路径,这个还是经常用做判断的。
String path = uriComponents.getPath();
// path = /spring-security/{article}
System.out.println("path = " + path);
提取 Query
提取路径中的 Query 参数可以说是我们最常使用的功能了。
String query = uriComponents.getQuery();
// query = version=1×tamp=123123325
System.out.println("query = " + query);
更加合理的提取方式:
MultiValueMap<String, String> queryParams = uriComponents.getQueryParams();