springspring-bootspring-webfluxspring-webclient

Spring WebClient Error - Reactor.core.publisher.LambdaMonoSubscriber cannot be cast to class org.springframework.web.client.RestClient


Following is the rest service that I have implemented

RestClient.RequestHeadersSpec<?> spec = (RestClient.RequestHeadersSpec<?>) webClient
                .post()
                .uri("/ValidateTaxId")
                .body(BodyInserters.fromValue(validateTaxIdRequestDTO))
                .accept(MediaType.APPLICATION_JSON)
                .header("jwtToken", validateTaxIdRequestDTO.getSessionHeaderRequestDTO().getJwtToken())
                .header("entidad", validateTaxIdRequestDTO.getSessionHeaderRequestDTO().getEntidad())
                .retrieve()
                .toEntity(ValidateTaxIdResponseDTO.class)
                .subscribe(result -> {
                    // get results as usual
                    final ValidateTaxIdResponseDTO validateTaxIdResponseDTO = result.getBody();
                    validateTaxIdResponseDTO.setMessage(result.getStatusCode().toString());

                    validateTaxIdResponseDTO.getSessionHeaderResponseDTO().setJwtToken(result.getHeaders().get("jwtToken").toString());

                    List<String> ti = result.getHeaders().get("transactionID");

                    // call the ui with the data
                    callback.operationFinished(validateTaxIdResponseDTO);

                }, error -> {

                    final ValidateTaxIdResponseDTO validateTaxIdResponseDTO = new ValidateTaxIdResponseDTO();

                    Throwable demo = error.getCause();

                    validateTaxIdResponseDTO.setValid(false);
                    validateTaxIdResponseDTO.setTaxIdFormated("");
                    validateTaxIdResponseDTO.setMessage("Error....");

                    // call the ui with the data
                    callback.operationFinished(validateTaxIdResponseDTO);

                });

The error I am getting is as follows.

java.lang.ClassCastException: class reactor.core.publisher.LambdaMonoSubscriber cannot be cast to class org.springframework.web.client.RestClient$RequestHeadersSpec (reactor.core.publisher.LambdaMonoSubscriber and org.springframework.web.client.RestClient$RequestHeadersSpec are in unnamed module of loader 'app')

Why is the error happening ? I can process it but I have the error in the console.

I followed this example.

https://howtodoinjava.com/spring-webflux/webclient-post-examples/#2-2-remote-api-returns-success-response-with-response-body


Solution

  • subscribe(...) return a Disposable, not RestClient.RequestHeadersSpec. Remove your cast and it will work