如何正确使用UriComponentsBuilder替换URL路径段完成占位符赋值
问题背景
待处理的URL模板格式如下:
http://example.com/{id}
需要将占位符{id}替换为实际值12,预期输出URL:
http://example.com/12
初始编写的实现代码:
url= "http://example.com/{id}"; UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url); builder.pathSegment("{id}", "12"); UriComponents uriComponents = builder.build().encode(); URI uri = uriComponents.toUri(); System.out.println(uri);
代码实际运行输出不符合预期,结果为:
http://example.com/%7Bid%7D/id/12
错误原因
pathSegment()方法的作用是在现有URL路径末尾追加新的路径片段,不会替换原有路径中的占位符,因此代码会在原路径后额外拼接/id/12- 未调用变量替换方法时,原路径中的
{id}不会被识别为待替换占位符,执行encode时{和}会被URL编码为%7B和%7D,最终出现%7Bid%7D的异常内容
正确实现方式
UriComponentsBuilder的路径占位符需要通过expand()方法传入实际值完成替换,以下是两种可直接运行的实现:
方式1:按顺序传入占位符值
适合占位符数量少、顺序固定的场景:
String url = "http://example.com/{id}"; URI uri = UriComponentsBuilder.fromUriString(url) .build() // 按占位符出现顺序传入对应实际值 .expand("12") .encode() .toUri(); System.out.println(uri); // 输出:http://example.com/12
方式2:通过键值对映射传入替换值
适合多占位符的场景,映射关系更清晰,不会出现顺序匹配错误:
String url = "http://example.com/{id}"; // 构建占位符名和实际值的映射 Map<String, Object> uriVariables = new HashMap<>(); uriVariables.put("id", 12); URI uri = UriComponentsBuilder.fromUriString(url) .build() .expand(uriVariables) .encode() .toUri(); System.out.println(uri); // 输出:http://example.com/12
补充说明:调用
build(true)可以开启URL严格校验模式,存在未替换的占位符时会直接抛出异常,避免生成非法URL。
内容的提问来源于stack exchange,提问作者Aniket
相关产品推荐
相关产品推荐

