Vijay Muvva
Vijay Muvva

Reputation: 1083

Spring WebFlux WebClient builder set request body

How do we set the request body in case of WebClient.Builder? Here is my code -

WebClient.Builder webClientBuilder = WebClient.builder().baseUrl(clientMetadataServiceUri).defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).filters(exchangeFilterFunctions -> {
        exchangeFilterFunctions.add(logRequest());
        exchangeFilterFunctions.add(logResponse());
    });

webClientBuilder.clientConnector(getHttpConnector()).build().get().exchange().doOnSuccess(clientResponse -> {...})

Where and how should I add the request body here?

Upvotes: 2

Views: 1638

Answers (2)

Vijay Muvva
Vijay Muvva

Reputation: 1083

The issue is with get() like many other frameworks Spring WebFlux also doesn't support the request body for the get calls. In the case of post, it goes like this -

    WebClient.Builder webClientBuilder = WebClient.builder().baseUrl(clientMetadataServiceUri).defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).filters(exchangeFilterFunctions -> {
        exchangeFilterFunctions.add(logRequest());
        exchangeFilterFunctions.add(logResponse());
    });

webClientBuilder.clientConnector(getHttpConnector()).build().post().body(...).exchange().doOnSuccess(clientResponse -> {...})

Upvotes: 0

pvpkiran
pvpkiran

Reputation: 27078

I believe it cannot be done.

Generally, WebClient(or RestTemplate) is like a template which you use to call other Rest Service. You define this template once with all the customizations needed like interceptors,messageConverters, errorHandlers etc which you need to communicate with this particular Service.

Now coming to individual calls to the service, each call to the service may vary. For example you might be calling different methods like Get, Post.. etc. You might call different endpoints. You might call with/without body. Since you always use the same client(WebClient/RestTemplate) to communicate with that service, you cannot create a WebClient instance with body or method or url(you can only set baseUrl) which are specific to individual call.

This is similar to RestTemplateBuilder. You cannot find any method to set either endpoint or method or body.

You might create a separate instance of webclient for each call. But that is not how it is generally used or advisable(Generally you define a bean of type WebClient and Autowire it). Hence it is not available.

Upvotes: 1

Related Questions