java - 如何使用 UriComponentsBuilder 对 URI 中的部分路径进行编码?
问题描述
我有一个看起来像这样的路径:/service/method/{id}/{parameters}
我使用 restTemplate 调用它,其中/service/method
是一个微服务,{id}
是我需要请求的一些 id,并且{parameters}
是一个看起来像这样的链接:/home/floor/kitchen/
我稍后在 JsonNodeTree 中用于映射服务/方法微服务。
我正在尝试使用
Map<String, String> uriVariables = new HashMap<String, String>();
uriVariables.put("id", "5080572115");
uriVariables.put("parameters", "/home/floor/kitchen/");
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("service/methods/{id}").
path("/{parameters}").buildAndExpand(uriVariables).encode();
String finalURI = uriComponents.toUriString();
return restTemplate.getForObject(finalURI, Integer.class);
但我得到的是整个链接http://service/methods/ {id}/{parameters} 编码。我只需要对其中的一部分({parameters})进行编码,这样我就可以将 url 的另一部分解析为 RestTemplate。再清楚一点,我需要将 service/methods/{id} 解析为 RestTemplate,然后解码 {parameters} 以用作 JsonNodeTree 的路径。
编辑:我知道查询,但找不到对路径的一部分进行编码的解决方案。
解决方案
要获得编码的路径变量,您需要使用pathSegment(String... pathSegments)
:
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("id", "5080572115");
uriVariables.put("parameters", "/home/floor/kitchen/");
UriComponents encode = UriComponentsBuilder.newInstance()
.scheme("http")
.host("localhost")
.path("service/methods")
.pathSegment("{id}", "{parameters}")
.buildAndExpand(uriVariables)
.encode();
System.out.println(encode);
输出
http://localhost/service/methods/5080572115/%2Fhome%2Ffloor%2Fkitchen%2F
推荐阅读
- javascript - 我对异步操作的理解正确吗?
- locust - 如何在 locust 中使用 css 选择器和 xpath 提取器?
- javascript - 打字稿,联合类型,元素隐含一个“任何”
- flutter - Flutter:弹出屏幕栈中的所有底层页面
- email - 在垃圾邮件中发送的电子邮件
- android - 如何在带有文本的列表视图中显示从 API 下载的图像
- alfresco - 如何在 Alfreso 中选择包含特定子项的文档?
- react-native - 我在做我的 react-native 项目时遇到了这个问题
- python - df['colimn_name'] vs df.loc[:, 'colimn_name']
- flutter - MaterialApp 中的 home 属性是运行应用程序所必需的吗?