Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactive WebClient GET Request with text/html response

Currently I’m having an issue with new Spring 5 WebClient and I need some help to sort it out. The issue is:

I request some url that returns json response with content type text/html;charset=utf-8.

But unfortunately I’m still getting an exception: org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/html;charset=utf-8' not supported. So I can’t convert response to DTO.

For request I use following code:

Flux<SomeDTO> response = WebClient.create("https://someUrl")
                .get()
                .uri("/someUri").accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToFlux(SomeDTO.class);

response.subscribe(System.out::println);

Btw, it really doesn’t matter which type I point in accept header, always returning text/html. So how could I get my response converted eventually?

like image 435
m13erok Avatar asked Jan 31 '18 23:01

m13erok


People also ask

How do I get JSON response from WebClient?

You would just use bodyToMono which would return a Mono object. WebClient webClient = WebClient. create(); String responseJson = webClient. get() .

Is WebClient reactive?

WebClient is a non-blocking, reactive client for performing HTTP requests with Reactive Streams back pressure. WebClient provides a functional API that takes advantage of Java 8 Lambdas.


1 Answers

As mentioned in previous answer, you can use exchangeStrategies method,

example:

            Flux<SomeDTO> response = WebClient.builder()
                .baseUrl(url)
                .exchangeStrategies(ExchangeStrategies.builder().codecs(this::acceptedCodecs).build())
                .build()
                .get()
                .uri(builder.toUriString(), 1L)
                .retrieve()
                .bodyToFlux( // .. business logic


private void acceptedCodecs(ClientCodecConfigurer clientCodecConfigurer) {
    clientCodecConfigurer.customCodecs().encoder(new Jackson2JsonEncoder(new ObjectMapper(), TEXT_HTML));
    clientCodecConfigurer.customCodecs().decoder(new Jackson2JsonDecoder(new ObjectMapper(), TEXT_HTML));
}
like image 187
guilhebl Avatar answered Sep 18 '22 02:09

guilhebl