【问题标题】:Add query parameter in WebClient request在 WebClient 请求中添加查询参数
【发布时间】:2020-05-11 22:09:17
【问题描述】:

我正在使用 Spring WebFlux,我正在接受请求并使用相同的请求来调用另一个服务。但我不确定如何添加查询参数。这是我的代码

@RequestMapping(value= ["/ptta-service/**"])
suspend fun executeService(request: ServerHttpRequest): ServerHttpResponse {

    val requestedPath = if (request.path.toString().length > 13) "" else request.path.toString().substring(13)

    return WebClient.create(this.dataServiceUrl)
                    .method(request.method ?: HttpMethod.GET)
                    .uri(requestedPath)
                    .header("Accept", "application/json, text/plain, */*")
                    .body(BodyInserters.fromValue(request.body))
                    .retrieve()
                    .awaitBody()
                    // But how about query parameters??? How to add those
}

虽然代码在 Kotlin 中,但 Java 也会有所帮助。

【问题讨论】:

    标签: java kotlin spring-webflux spring-webclient


    【解决方案1】:

    您可以在uri 中使用lambda 表达式添加查询参数,更多信息请参阅WebClient.UriSpec

     return WebClient.create(this.dataServiceUrl)
                    .method(request.method ?: HttpMethod.GET)
                    .uri(builder -> builder.path(requestedPath).queryParam("q", "12").build())
                    .header("Accept", "application/json, text/plain, */*")
                    .body(BodyInserters.fromValue(request.body))
                    .retrieve()
                    .awaitBody()
    

    【讨论】:

    • 谢谢你的解决方案是 Kotlin 中的 .uri { builder -> builder.path(requestedPath).queryParams(request.queryParams).build() }。但你的建议是正确的。
    猜你喜欢
    • 1970-01-01
    • 2021-05-13
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 2019-03-20
    • 1970-01-01
    • 2021-06-04
    相关资源
    最近更新 更多