如何使用UriComponentsBuilder在URI中编码路径的一部分?

问题描述 投票:0回答:2

我有一个看起来像这样的路径:/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的路径。

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

java spring spring-boot encode encodeuricomponent
2个回答
0
投票

[我不太确定您是否理解这不是使用as @PathVariable批注的正确方法,这表明方法参数应绑定到URI模板变量。您需要使用@RequestParam批注,该批注指示应将方法参数绑定到Web请求参数。然后,您可以通过以下方式进行管理:/home/{id}?parameters=floor,kitchen然后您的代码应该会看到类似以下内容:

@GetMapping("/get/{id}")
public ResponseEntity<XXXXX> getXXXXX(@PathVariable id,
                                      @RequestParam List<String> parameters)) {
    return ResponseEntity.ok().body(service.getXXX(id, parameters));
}

0
投票

要获得编码的路径变量,您需要使用pathSegment(String... pathSegments)

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);
© www.soinside.com 2019 - 2024. All rights reserved.