簡體   English   中英

SpringBoot Webflux無法返回application / xml

[英]SpringBoot Webflux cannot return application/xml

在我的反應性REST API中,我試圖返回XML響應。 但是,我總是得到一個JSON ,即406 NOT_ACCEPTABLE 知道為什么嗎?

@RestController
@RequestMapping(path = "/xml", produces = APPLICATION_XML_VALUE)
public class RestApi {
    @GetMapping(path = "/get")
    public Publisher<ResponseEntity> get() {
        return Mono.just(ResponseEntity.ok().contentType(APPLICATION_XML).body(new Datta("test")));
    }

    @PostMapping(path = "/post", consumes = APPLICATION_XML_VALUE)
    public Publisher<ResponseEntity<Datta>> post(@RequestBody Datta datus) {
        datus.setTitle(datus.getTitle() + "!");
        return Mono.just(ResponseEntity.ok().contentType(APPLICATION_XML).body(datus));
    }
}

java.lang.AssertionError:預期的:application / xml實際的:application / json; charset = UTF-8

plugins {
    id 'org.springframework.boot' version '2.1.3.RELEASE'
    id "io.spring.dependency-management" version "1.0.7.RELEASE"
}
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    implementation "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.9.8"
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

這些是我的REST 控制器單元測試的鏈接。 謝謝!

顯然, jackson-dataformat-xml 尚不支持WebFlux中的XML編組。 到目前為止,我看到兩種可能性:

  1. 在類路徑上添加org.springframework.boot:spring-boot-starter-web (應該同時包含starter-webstarter-webflux )。 但是,這僅適用於Servlet 3.1運行時(例如Tomcat)。
  2. 或者,如果您希望使用完整的反應式Web服務器(例如Netty),請使用 JAXB中的xml編組( Jaxb2XmlEncoderJaxb2XmlDecoder ):

build.gradle

sourceCompatibility = '11'

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

    // Java 11 removed these Java EE modules
    implementation "javax.xml.bind:jaxb-api:2.3.1"
    implementation "com.sun.xml.bind:jaxb-core:2.3.0.1"
    implementation "com.sun.xml.bind:jaxb-impl:2.3.2"

    compileOnly "org.projectlombok:lombok"
    annotationProcessor "org.projectlombok:lombok"
}

POJO

@Data
@AllArgsConstructor
@NoArgsConstructor
@XmlRootElement
public class Datta {
    private String title;
}

注意3個javax.xml.bind依賴項(對於Java 8不需要這些依賴項)和@XmlRootElement批注。 該解決方案可以立即WebFluxConfigurer ,但是,如果您需要進一步的自定義,請實現自己的WebFluxConfigurer

@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {
    @Override
    public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        configurer.registerDefaults(false);
        configurer.customCodecs().decoder(new Jaxb2XmlDecoder());   // <- here
        configurer.customCodecs().encoder(new Jaxb2XmlEncoder());   // <- here

    }
}

是源代碼的鏈接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM