如何在Spring boot中的Web客户端中按名称传递路径变量?

Pra*_*bhu 7 java spring-boot spring-webclient

我想在网络客户端中使用名称传递路径变量。我可以通过键值对传递查询参数,但如何传递路径变量。

对于查询参数,我们可以通过传递键值对来做到这一点

 this.webClient.get()
  .uri(uriBuilder - > uriBuilder
    .path("/products/")
    .queryParam("name", "AndroidPhone")
    .queryParam("color", "black")
    .queryParam("deliveryDate", "13/04/2019")
    .build())
  .retrieve();
Run Code Online (Sandbox Code Playgroud)

对于路径变量,我们可以通过传递值来做到这一点

this.webClient.get()
  .uri(uriBuilder - > uriBuilder
    .path("/products/{id}/attributes/{attributeId}")
    .build(2, 13))
  .retrieve();
Run Code Online (Sandbox Code Playgroud)

我想要像下面这样

this.webClient.get()
  .uri(uriBuilder - > uriBuilder
    .path("/products/{id}/attributes/{attributeId}/")
    .pathParam("attributeId", "AIPP-126")
    .pathParam("id", "5254136")
    .build())
  .retrieve();
Run Code Online (Sandbox Code Playgroud)

Puc*_*uce 8

除了 @boobalan 的 anwser 之外,提到的案例最简单的方法是:

   webClient.get()
    .uri("/products/{id}/attributes/{attributeId}", 2, 13)
    .retrieve();
Run Code Online (Sandbox Code Playgroud)


boo*_*lan 1

这是一个设计决定

为什么要构造一个 There forqueryParam而不是 for pathParam

对于查询参数,任何查询参数在 uri 中出现的顺序并不重要,只需.queryParam("name", "AndroidPhone")在 uri 中声明一次(和赋值)URIBuilder就足够了。

然而,在 的情况下path param,任何或不同路径参数在 uri 中出现的顺序很重要:

您的建议强制在 URI 中的确切相对位置中声明任何pathParam类似内容attributeId一次,并分别为其分配值,这要求用户总共attributeId提供两次正确的文本输入。attributeId

取而代之的是,URIBuilder has 构造仅声明所有唯一一次,同时按顺序path params声明并传递所有值。.build(..)