【发布时间】:2019-11-23 18:34:35
【问题描述】:
使用 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>
触发对外部 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));
ServiceResponse 类(一个简单的 POJO):
public class ServiceResponse {
private String ack;
private String version;
private String timestamp;
// .. getters and setters
产生的错误:
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] at 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' ?
【问题讨论】:
-
杰克逊适用于 JSON。您需要 JAXB 才能使用 XML。
-
你可以试试 application/xml stackoverflow.com/questions/3272534/…
-
@guilhebl 我仍然面临这个错误。您找到解决方案了吗?
标签: java spring spring-boot jackson spring-webflux