java url帮助类_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&timestamp=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 = httpsSystem.out.println("scheme = " + scheme);

提取 Host

获取host也是很常见的操作。

String host = uriComponents.getHost();

// host = felord.cnSystem.out.println("host = " + host);

提取 Port

获取 uri 的端口。

int port = uriComponents.getPort();

// port = -1System.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&timestamp=123123325System.out.println("query = " + query);

更加合理的提取方式:

MultiValueMap queryParams = uriComponents.getQueryParams();

// queryParams = {version=[1], timestamp=[123123325]}System.out.println("queryParams = " + queryParams);

填充路径参数

假如我们想填充章节 2中代码中声明的的httpUrl中的路径参数{article},我们可以这样:

UriComponents expand = uriComponents.expand("oauth2-authorization-request.html");

//expand = https://felord.cn/spring-security/oauth2-authorization-request.html?version=1&timestamp=123123325System.out.println("expand = " + expand);

4. 总结

Spring 作为目前 Java Web 开发中几乎不可避免的框架其实已经提供了很多有用的工具来方便我们操作。UriComponents只是其中一个用于操作URI的工具,今天我们对它的一些常用功能进行了演示,希望能够帮你解决一些相关的操作难题。原作者:码农小胖哥

原文链接:Spring居然还提供了这么好用的URL工具类

原出处:公众号

侵删

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值