【问题标题】:How to encode a portion of path in URI using UriComponentsBuilder?如何使用 UriComponentsBuilder 对 URI 中的部分路径进行编码?
【发布时间】:2019-11-24 03:36:42
【问题描述】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我不太确定您是否理解这不是使用 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));
      }
      

      【讨论】:

        猜你喜欢
        • 2022-12-14
        • 1970-01-01
        • 2022-12-01
        • 2013-04-09
        • 2020-08-04
        • 2011-04-16
        • 1970-01-01
        • 1970-01-01
        • 2015-08-22
        相关资源
        最近更新 更多