如何使用 Spring Webclient 在 GET URL 上传递 JSON

jef*_*ter 1 spring spring-webclient

我需要使用如下所示的 URL 调用外部服务...

获取https://api.staging.xxxx.com/locations?where={"account":"bob"}

这不是我的服务,我对其没有影响力,我目前的代码库正在使用 Spring WebClient。

WebClient.create("https://api.staging.xxxx.com/")
.get()
.uri(uriBuilder -> uriBuilder.path("locations?where={'account':'bob'}").build())
Run Code Online (Sandbox Code Playgroud)

由于 WebClient 看到 { 括号,它会尝试将值注入到 URL 中,但我不希望这样做。

谁能建议我如何使用 Spring WebClient?

否则我将恢复到 OKHttp 或另一个基本客户端来发送此请求。

lka*_*ris 5

您可以使用UriUtils#encodeQueryParams对 JSON 参数进行编码:

String whereParam = "{\"account\":\"bob\"}";

 //...
uriBuilder
   .path("locations")
   .queryParam("where", UriUtils.encodeQueryParam(whereParam, StandardCharsets.UTF_8))
   .build()
Run Code Online (Sandbox Code Playgroud)