Home > Net >  How to pass JSON on a GET URL with Spring Webclient
How to pass JSON on a GET URL with Spring Webclient

Time:10-07

I need to call an external service with URL that looks like this...

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

This is not my service and I have no influence over it, and my codebase at the moment is using Spring WebClient.

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

Since WebClient sees the { bracket it tries to inject a value into the URL, which I don't want.

Can anyone suggest how I can do with with Spring WebClient?

Otherwise I will revert to OKHttp or another basic client to sent this request.

CodePudding user response:

One way to achieve this is to manually url encode the values before passing them to the uri builder.

Also I think that you should use queryParam() to specify query parameters.

uriBuilder -> 
  uriBuilder.path("locations")
            .queryParam("where", "{'account': 'bob'}")
            .build()

Another option would be to configure the encoding mode when creating the WebClient

 DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory();
 factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
 WebClient.builder().uriBuilderFactory(factory).build();

CodePudding user response:

You can use UriUtils#encodeQueryParams to encode the JSON param:

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

 //...
uriBuilder
   .path("locations")
   .queryParam("where", UriUtils.encodeQueryParam(whereParam, StandardCharsets.UTF_8))
   .build()
  • Related