org.springframework.web.reactive.function.UnsupportedMediaTypeException:bodyType 不支持内容类型“text/xml;charset=UTF-8”

gui*_*ebl 7 java spring jackson spring-boot spring-webflux

使用 Java 11、SpringBoot 2、WebFlux、WebClient 和 Jackson

尝试使用 Spring WebClient 来使用返回 XML 的 Web 服务端点,内容类型:'text/xml;charset=UTF-8'

项目的 pom.xml 中的 Jackson XML 依赖项:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.9</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

触发对外部 API 的请求并构建响应的 WebClient 代码:

        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));
Run Code Online (Sandbox Code Playgroud)

ServiceResponse 类(一个简单的 POJO):

public class ServiceResponse {

    private String ack;
    private String version;
    private String timestamp;
// .. getters and setters
Run Code Online (Sandbox Code Playgroud)

结果错误:

org.springframework.web.reactive.function.UnsupportedMediaTypeException: 不支持内容类型 'text/xml;charset=UTF-8'对于 bodyType=com.sample.service.model.ServiceResponse 在 org.springframework.web.reactive.function.BodyExtractors.lambda$readWithMessageReaders$12(BodyExtractors.java:201) ~[spring-webflux-5.1.8.RELEASE.jar: 5.1.8.RELEASE] 在 java.base/java.util.Optional.orElseGet(Optional.java:369) ~[na:na] 在 org.springframework.web.reactive.function.BodyExtractors.readWithMessageReaders(BodyExtractors.java: 197) ~[spring-webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE] 在 org.springframework.web.reactive.function.BodyExtractors.lambda$toMono$2(BodyExtractors.java:85) ~[spring- webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE] 在 org.springframework.web.reactive.function.client.DefaultClientResponse.body(DefaultClientResponse.java:95) ~[spring-webflux-5.1.8.RELEASE .jar:5.1.8.RELEASE] 在 org.springframework.web.reactive.function.client。DefaultClientResponse.bodyToMono(DefaultClientResponse.java:113) ~[spring-webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE]

如何正确使用响应类型: Content-type 'text/xml;charset=UTF-8'

Bri*_*zel 5

Spring Framework 目前不支持 Jackson XML - 请参阅专门的问题。同时,您可以将 Jaxb 与Jaxb2XmlEncoder和 一起使用Jaxb2XmlDecoder