首页 > 解决方案 > 如何使用 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 的路径。

编辑:我知道查询,但找不到对路径的一部分进行编码的解决方案。

标签: javaspringspring-bootencodeencodeuricomponent

解决方案


要获得编码的路径变量,您需要使用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

推荐阅读