记录贴:项目中有用到构造URL用于重定向的方式,之前也做过几次,但是没有记录,每次都需要寻找记录,但有的优秀博文可能会随时间流逝而丢失,于是做个记录和整合。
参考链接:
UriComponentsBuilder 拼装 url
Java UriComponentsBuilder.fromUriString方法代碼示例
1.引入依赖
<!--因为UriComponentsBuilder是org.springframework.web.util下的-->
<!--对于Spring boot项目,已经再此依赖下引入-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--对于maven项目-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
2.主要接口
这个类是一个建造者模式,我们可以通过几个办法来构建我们的url(最后的类就是UriComponents),这个时候我们可以再通过这个类去重定向或者生成URL的String都可以。
构造方法,可以看到还是有很多的,我记录几个比较常用的,之后要是有再用到我再更新吧。
// 其实在源码的英文文档注释是说的很清楚,推荐大家直接看源码注释,我这边做一个简单的阐述
// 构建一个空的请求,没有域名,参数等等。需要自己一步步构造,
public static UriComponentsBuilder newInstance()
// 传入path,以提供的path初始化,不能包含http/https host 都会识别为pat,详情参见[解释1]
public static UriComponentsBuilder fromPath(String path)
// 根据传入的URI类构造
public static UriComponentsBuilder fromUri(URI uri)
// String uriString = "/hotels/42?filter={value}";
public static UriComponentsBuilder fromUriString(String uri)
// 传入http字符串,有格式要求
// 源码中的注释 String urlString = "https://example.com/hotels/42?filter={value}";
public static UriComponentsBuilder fromHttpUrl(String httpUrl)
// 根据传入的request 构建一个相同的请求
public static UriComponentsBuilder fromHttpRequest(HttpRequest request)
- 解释1:
所以不行,无法识别的协议、域名、路径、参数。传入的字符串都默认为path
3.生成URI
其实还可以设置其他参数,可以直接看源码了解
UriComponents uri = UriComponentsBuilder
.fromHttpUrl("https://open.weixin.qq.com/connect/oauth2/authorize")
.queryParam("appid", "appid")
.queryParam("redirect_uri", "")
.queryParam("response_type", "code")
.queryParam("scope", "SCOPE")
.queryParam("state", "state=123")
.build();
// 如果想要再后面拼接参数,只有采用字符串拼接的方式了
System.out.println(uri.toUriString()+"#wechat_redirect");