Looking for an alternative of retryWhen which is now Deprecated

Issue I’m facing an issue with WebClient and reactor-extra. Indeed, I have the following method : public Employee getEmployee(String employeeId) { return webClient.get() .uri(FIND_EMPLOYEE_BY_ID_URL, employeeId) .retrieve() .onStatus(HttpStatus.NOT_FOUND::equals, clientResponse -> Mono.empty()) .onStatus(HttpStatus::is5xxServerError, clientResponse -> Mono.error(new MyCustomException(“Something went wrong calling getEmployeeById”))) .bodyToMono(Employee.class)

Continue reading

Return the complete response using Spring WebClient

Issue I have the following code public ClientResponse doGet(HttpServletRequest request, URI uri) { return webClient.get() .uri(uri.toASCIIString()) .headers(headers -> headers.putAll(processRequest(request)) .exchange() .block(); } But when I try to return this ClientResponse through the RestController as follows, @GetMapping @ResponseBody public ClientResponse doGet(HttpServletRequest

Continue reading

How to use WebClient to execute synchronous request?

Issue Spring documentation states that we have to switch from RestTemplate to WebClient even if we want to execute synchronous http call. For now I have following code: Mono<ResponseEntity<PdResponseDto>> responseEntityMono = webClient.post() .bodyValue(myDto) .retrieve() .toEntity(MyDto.class); responseEntityMono.subscribe(resp -> log.info(“Response is {}”,

Continue reading

How to wait until List<Mono<List<Object>>> finishes?

Issue It’s my first time working with webClient and I am wondering how to wait until List<Mono<>> finishes. I have the following code: List<Address> addresses = collectAllAddresses(someObject); List<Mono<List<AnotherAddress>>> monoResponses = addresses.stream() .map(address -> webClientGateway.findAddresses(userData, address.getFullAddress())) .collect(Collectors.toList()); Mono.when(monoResponses).block(); log.info("mono responses"); monoResponses.stream()

Continue reading

Spring WebClient: What is the default multiplier for Retry.backoff?

Issue I am trying to understand the the default multiplier for exponential backoff strategy for Spring WebClient Retry.backoff method. And can this be configured? I cannot find documentation for this. https://projectreactor.io/docs/core/release/api/reactor/util/retry/Retry.html#backoff-long-java.time.Duration- Version: reactor-netty 0.9.12.RELEASE Solution The utility method Retry.backoff, as

Continue reading

How to set TCP Keepalive in Reactor Netty HTTP client?

Issue I saw that HttpClient.from(TcpClient.create().option(ChannelOption.SO_KEEPALIVE, true)) from method was deprecated. How currently am I supposed to set SO_KEEPALIVE using HttpClient.create()? Solution It was easier that I thought: HttpClient.create().option(ChannelOption.SO_KEEPALIVE, true) Answered By – pixel Answer Checked By – Gilberto Lyons (AngularFixing

Continue reading

Spring WebFlux switchIfEmpty to return different type

Issue public Mono<ServerResponse> getMessage(ServerRequest request) { //this call returns Mono<ApiClientResponse> return apiClient.hystrixWrappedGetMessages(request.headers().asHttpHeaders(), request.queryParams()) .switchIfEmpty(/* Here */) } Excuse the slightly incomplete code, I was restructuring it when I ran into this problem. The gist is that where it says /*

Continue reading

How to set onStatus in Spring WebClient builder instance

Issue I’ve got a lot of methods that use the onStatus API from Spring’s WebClient: @Override public Mono<Accommodation> createAccommodation(CreateAccommodation create) { return webClient .post() .contentType(APPLICATION_JSON) .bodyValue(create) .retrieve() .onStatus(HttpStatus::isError, clientResponse -> clientResponse .bodyToMono(ApiErrorResponse.class) .flatMap(errorResponse -> Mono.error(new ResponseStatusException( HttpStatus.valueOf(errorResponse.getStatus()), errorResponse.getMessage() )))) .bodyToMono(Accommodation.class);

Continue reading

Cannot parse Google geocode json object via webclient

Issue I try to call following webclient query: return webClient .get() .uri(uriBuilder -> uriBuilder .path("/geocode/json") .queryParam("key", google.getApiKey()) .queryParam("latlng", String.join( ",", String.valueOf(point.getLat()), String.valueOf(point.getLng())) ) .build()) .accept(MediaType.APPLICATION_JSON) .retrieve() .onStatus(HttpStatus::isError, RestErrorHandler::manageError) .bodyToMono(*PlacesSearchResponse.class*); REST operation from google returns (https://developers.google.com/maps/documentation/geocoding/overview#GeocodingResponses) following object: { "results" :

Continue reading

Spring Boot – WebClient – multipart response – How to get the binary data

Issue Here is my code to call a REST-Service String result = webClient.post() .body(BodyInserters.fromMultipartData(bodyBuilder.build())) .exchangeToMono(clientResponse -> clientResponse.bodyToMono(String.class)) .block(); This works fine. I get a HTTP-Status 200. Response Header Content-Type: multipart/form-data; boundary="n1OnMVB:z)VeTRs)kd9:h8Hz9H+_kywMV2mb)MWu." Body –n1OnMVB:z)VeTRs)kd9:h8Hz9H+_kywMV2mb)MWu. Content-Disposition: form-data; name="lastname" smith –n1OnMVB:z)VeTRs)kd9:h8Hz9H+_kywMV2mb)MWu. Content-Disposition: form-data;

Continue reading

What would be the proper way to pass custom exception from Kotlin Webclient awaitExchange Lambda function to web controller?

Issue Working on a new microservice that’s using reactive WebClient to call another microservice. Here is what I have: Controller.kts @GetMapping(["/books/{id}"], produces = [MediaType.APPLICATION_JSON_VALUE]) suspend fun getBook(…): ResponseEntity<Any> { val book = service.getBook(id) return Response.ok().body(book) } Service.kts suspend fun getBook(id:

Continue reading

How add or Ignoring a specific http status code in WebClient reactor?

Issue I have a this method that manage all request of my project: private Mono<JsonNode> postInternal(String service, String codPayment, String docNumber, RequestHeadersSpec<?> requestWeb) { return requestWeb.retrieve().onStatus(HttpStatus::is4xxClientError, clientResponse -> clientResponse.bodyToMono(ErrorClient.class).flatMap( errorClient -> clientError(service, codPayment, clientResponse.statusCode(), docNumber, errorClient))) .onStatus(HttpStatus::is5xxServerError, clientResponse -> clientResponse.bodyToMono(ErrorClient.class)

Continue reading

Spring WebClient header from ReactiveSecurityContext

Issue I’m trying to set WebClient header value accordingly to the authenticated user, something like this: webClient.post().header(HttpHeaders.AUTHORIZATION, getUserIdFromSession())… and public String getUserIdFromSession() { Mono<Authentication> authentication = ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication); //do something here to get user credentials and return them } Should I

Continue reading

java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory

Issue Spring boot version 2.4.4 Java version 15 @Bean public WebClient webClient() { return WebClient.builder().baseUrl(BASE_URL) .defaultHeaders(header -> header.setBasicAuth("test", "testpwd")) .clientConnector(new ReactorClientHttpConnector(HttpClient.newConnection())) .exchangeStrategies(ExchangeStrategies.builder().codecs(configurer -> { configurer.defaultCodecs().jaxb2Encoder(new Jaxb2XmlEncoder()); configurer.defaultCodecs().jaxb2Decoder(new Jaxb2XmlDecoder()); }).build()).build(); } Using Spring boot 2.4.4 webclient and trying to consume the

Continue reading

How to use Flux to write Json Pojo to a CSV

Issue The following function will retrieve a List of String. During the merge process, rather then print the output I would like to write the output to a CSV file. List<Mono<Device>> list1 = page.get().map(device -> webClient.post() .uri(uri) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header(HttpHeaders.ACCEPT,

Continue reading

Getting some httpHeader in spring webclient call

Issue In my spring boot 2.4.1 application, I’m using WebClient for invoking some external rest services. In reqular scenario it’s pretty straightforward and works fine as I expected: InquiryChequeResponse response=webClient.post() .uri(inquiryChequeUrl) .body(Mono.just(requestDto), InquiryChequeReq.class) .exchangeToMono(res -> { return res.bodyToMono(InquiryChequeResponse.class); }).block(); But

Continue reading

Correct URL encoding of # Java WebClient

Issue I’m tring to use this code to retrieve data from my API: Mono<String> client = WebClient.builder() .baseUrl("https://localhost:8081/getPost/" + id) // or URLEncoder.encode(id, "UTF-8") .defaultHeaders(new Consumer<HttpHeaders>() { @Override public void accept(HttpHeaders httpHeaders) { httpHeaders.addAll(createHeaders()); } }) .build() .get() .retrieve() .bodyToMono(String.class);

Continue reading

Get status code of Spring WebClient request

Issue My goal is to get the HttpStatus from a Spring WebClient request. All other information of the request is irrelevant. My old way of doing this was: WebClient.builder().baseUrl("url").build() .get().exchange().map(ClientResponse::statusCode).block(); With Spring Boot 2.4.x/Spring 5.3, the exchange method of WebClient

Continue reading

WebClient ExchangeFilterFunction JUnit

Issue How do I get code coverage for ClientResponseErrorService.genericClientFilter? @PostConstruct public void init() throws SSLException { SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); HttpClient httpClient = HttpClient.create().secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); ClientHttpConnector restConnector = new ReactorClientHttpConnector(httpClient); webClient = WebClient.builder() .baseUrl(basePath) .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)

Continue reading

Sending a json string as query parameter via spring web client

Issue I am trying to use the code below to send across a json string as a query param using Spring WebClient. var client = WebClient.builder() .baseUrl(baseurl) .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .build() client.post().uri(uriBuilder -> uriBuilder.path("/api/SomeRequest") .queryParam("response", responseJsonStr).build() ).retrieve().bodyToMono(ReponseObj.class).block() I am seeing a

Continue reading

WebClient GET unit test with mockito

Issue I am facing issue with Webclient and mockito Below is my service code: public Flux<Config> getConfigs(String param1, String param2) { MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(); if(!StringUtils.isEmpty(param2)) { queryParams.add("name", param2); } String path = "api/v1/config"; return webClient.get().uri(uriBuilder -> uriBuilder.path(path)

Continue reading

How to use webClient in Spring Integration?

Issue I’m trying to use webClient in my Spring Integration application. Using block() method i got this error: org.springframework.messaging.MessageHandlingException: error occurred during processing message in ‘MethodInvokingMessageProcessor’ [org.springframework.integration.handler.MethodInvokingMessageProcessor@28b67bb]; nested exception is java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread

Continue reading

replacing an OAuth2 WebClient in a test

Issue I have a small Spring Boot 2.2 batch that writes to an OAuth2 REST API. I have been able to configure the WebClient following https://medium.com/@asce4s/oauth2-with-spring-webclient-761d16f89cdd and it works as expected. @Configuration public class MyRemoteServiceClientOauth2Config { @Bean(“myRemoteService”) WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations)

Continue reading

adding JWT token in request in reactive way in webflux

Issue I am using WebClient to call Rest API Which are secured by JWT token. //To get Token JwtToken token = client.post() .uri(“”) .body(BodyInserters.fromFormData(“username”, “XXX”) .with(“password”, “XXXXX”)) .retrieve() .bodyToFlux(JwtToken.class) .onErrorMap(e -> new Exception(“Error While getting Token”, e)) .blockLast(); //Call secure

Continue reading