1。前言在开发中,我们经常对URL进行操作,比如提取端口、提取路径,以及最常用的提取参数。很多时候需要借助一些第三方类库或者自己编写工具类。今天胖哥给大家介绍一个方法,不需要引入新的类库。只要使用SpringWeb模块,就可以轻松完成URL。组装和拆卸提取。2、UriComponentsJDK虽然提供了java.net.URI,但是还是不够强大,所以Spring封装了一个不可变的URI来表示org.springframework.web.util.UriComponents。UriComponentsBuilder我们可以使用它的构造类UriComponentsBuilder从URI、Http链接和URI路径来初始化UriComponents。以Http链接为例:StringhttpUrl="https://felord.cn/spring-security/{article}?version=1×tamp=123123325";UriComponentsuriComponents=UriComponentsBuilder.fromHttpUrl(httpUrl).build();如果不是Http,则不能使用上面的方法后,需要使用fromUriString(Stringuri)。我们也可以直接构造一个UriComponents:UriComponentshttps=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=95273。操作UriComponents提取协议头如果要提取协议头,如上例,我们要提取https。Stringscheme=uriComponents.getScheme();//scheme=httpsSystem.out.println("scheme="+scheme);ExtractingHost获取host也是一个很常见的操作。Stringhost=uriComponents.getHost();//host=felord.cnSystem.out.println("host="+host);ExtractPort得到uri的端口。intport=uriComponents.getPort();//port=-1System.out.println("port="+port);但是很奇怪上面是-1,很多人误以为会是80。其实Http协议确实是80,但是java.net.URL#getPort()规定如果URL实例没有声明(省略)端口号,返回值为-1。所以当返回-1时,它相当于80,但它们并没有直接反映在URL中。ExtractPath提取路径,常用于判断。Stringpath=uriComponents.getPath();//path=/spring-security/{article}System.out.println("path="+path);ExtractQuery提取路径中的Query参数可以说是我们现在最常用的功能了。Stringquery=uriComponents.getQuery();//query=version=1×tamp=123123325System.out.println("query="+query);更合理的提取方式:MultiValueMap
