Introduction to Webclient

Introduction to Webclient

Webclient is Non-blocking, reactive client interface to perform web requests. It come under webflux library. To use WebClient api, we must have spring-boot-starter-webflux module imported into the project.

File name - pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

We can configure Webclient through one of the static factory methods:

  1. WebClient.create()

  2. WebClient.create(String baseUrl)

Example for GET Requests:-

Mono<ResponseEntity<String>> conn1 = WebClient.create("https://bigquery.googleapis.com/bigquery/v2")
                        .get()
                        .uri(uriBuilder -> uriBuilder.path("/projects/{projectId}/datasets/{datasetId}/tables" )
                        .queryParam("access_token", accessToken)
                        .build(projectId, datasetId))
                        .retrieve().toEntity(String.class);
String val = conn2.block().getBody();

Here,

  1. Query Parameters are key and value pairs separated by an ampersand (&) and they appear at the end of a URL, after a question mark (?).

  2. The UriBuilder function replaces the {projectId}, {datasetId} token with the value provided in the build() method.

  3. The retrieve() method directly performs the HTTP request and retrieve the response body.

Example for POST Requests:-

Mono<ResponseEntity<String>> conn2 =WebClient.create("https://bigquery.googleapis.com/bigquery/v2")
                        .post()
                        .uri(uriBuilder -> uriBuilder.path("/projects/{projectId}/queries" )
                        .queryParam("access_token", accessToken)
                        .build(projectId))
                        .body(BodyInserters.fromValue(query))
                        .retrieve().toEntity(String.class);

                String  val = conn2.block().getBody();