I’m having an issue with Spring 5 reactive WebClient, when I request an endpoint that returns a correctly formated json response with content type "text/plain;charset=UTF-8". The exception is
org.springframework.web.reactive.function.UnsupportedMediaTypeException:
Content type 'text/plain;charset=UTF-8' not supported for bodyType=MyDTOClass
Here is how I made the request:
webClient.get().uri(endpoint).retrieve().bodyToFlux(MyDTOClass.class)
EDIT: Headers are "correctly" setted (Accept, Content-Type), I have tried differents content-types (json, json + UTF8, text plain, text plain + UTF8) conbinations, without success. I think the issue is .bodyToFlux(MyDTOClass.class)
doesn't know how to translate "text" into MyDTOClass
objects.
If I change the request to:
webClient.get().uri(endpoint).retrieve().bodyToFlux(String.class)
I can read the String.
EDIT 2: The next quote is extracted from the Spring documentation (https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-codecs-jackson)
By default both
Jackson2Encoder
andJackson2Decoder
do not support elements of typeString
. Instead the default assumption is that a string or a sequence of strings represent serialized JSON content, to be rendered by theCharSequenceEncoder
. If what you need is to render a JSON array fromFlux<String>
, useFlux#collectToList()
and encode aMono<List<String>>
.
I think the solution is define a new Decoder/Reader in order to transform the String into MyDTOClass, but i don't know how to do it.
this.webClient = WebClient.builder() .baseUrl(clientUrl) .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_UTF8_VALUE) .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE) .build();
– Wheezy.bodyToFlux(String.class)
and my DTO match perfectly with the response.I manualy extracted the response to a file in my resources directory with the nameresponse.json
and I can read it without problem pointing the webclient to localhost/response.json, If I change the file extension toresponse.txt
it throws the same exception. – Detain