Skip to content

org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type ‘text/xml;charset=UTF-8’ not supported for bodyType

using Java 11, SpringBoot 2, WebFlux, WebClient and Jackson

trying to use Spring WebClient to consume a Web service endpoint that returns XML, content type: ‘text/xml;charset=UTF-8’

Jackson XML dependency in the project’s pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.9</version>
</dependency>

WebClient code that triggers a request to external API and builds the response:

        WebClient.builder()
                .baseUrl(url)
                .build()
                .get()
                .uri(builder.toUriString(), 1L)
                .accept(TEXT_XML)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_XML_VALUE)
                .acceptCharset(Charset.forName("UTF-8"))
                .exchange()
                .flatMap(x -> x.bodyToMono(ServiceResponse.class))
                .flatMap(x -> buildResponse(x));

ServiceResponse class (a simple POJO):

public class ServiceResponse {

    private String ack;
    private String version;
    private String timestamp;
// .. getters and setters

resulting error:

org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type ‘text/xml;charset=UTF-8’ not supported for bodyType=com.sample.service.model.ServiceResponse at org.springframework.web.reactive.function.BodyExtractors.lambda$readWithMessageReaders$12(BodyExtractors.java:201) ~[spring-webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE] at java.base/java.util.Optional.orElseGet(Optional.java:369) ~[na:na] at org.springframework.web.reactive.function.BodyExtractors.readWithMessageReaders(BodyExtractors.java:197) ~[spring-webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.web.reactive.function.BodyExtractors.lambda$toMono$2(BodyExtractors.java:85) ~[spring-webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.web.reactive.function.client.DefaultClientResponse.body(DefaultClientResponse.java:95) ~[spring-webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.web.reactive.function.client.DefaultClientResponse.bodyToMono(DefaultClientResponse.java:113) ~[spring-webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE]

how to properly consume the type of response: Content-type ‘text/xml;charset=UTF-8’ ?

Answer

Jackson XML is not supported at the moment by Spring Framework – see the dedicated issue. In the meantime, you can use Jaxb with Jaxb2XmlEncoder and Jaxb2XmlDecoder.