Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add query parameter in WebClient request

I am using Spring WebFlux where I am taking request and using same request to call another service. But I am not sure how to add query parameters. This is my code

@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
}

Though code is in Kotlin, Java will help as well.

like image 274
nicholasnet Avatar asked Jan 26 '20 05:01

nicholasnet


People also ask

How do I pass a query parameter in WebClient?

In order to pass single value query parameters, create a path of the base resource URI and then use queryParam() method to append key value pairs.

How send parameters in HTTP GET request?

To use this function you just need to create two NameValueCollections holding your parameters and request headers. Show activity on this post. You can also pass value directly via URL. If you want to call method public static void calling(string name){....}

Does WebClient use Netty?

WebClient provides a higher level API over HTTP client libraries. By default it uses Reactor Netty but that is pluggable with a different ClientHttpConnector.

How do I log a body response in WebClient?

Logging Request and Response with Body HTTP clients have features to log the bodies of requests and responses. Thus, to achieve the goal, we are going to use a log-enabled HTTP client with our WebClient. We can do this by manually setting WebClient. Builder#clientConnector – let's see with Jetty and Netty HTTP clients.


Video Answer


1 Answers

You can add the query parameters using lambda expression in uri, for more information see 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()
like image 108
Deadpool Avatar answered Sep 30 '22 17:09

Deadpool