【发布时间】:2019-08-13 19:53:17
【问题描述】:
在我的反应式 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: 预期:应用程序/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 controller 和 unit test 的链接。谢谢!
【问题讨论】:
-
afaik 您应该使用 API 方法上方的 @RequestMapping(produces=APPLICATION_XML_VALUE),而不是 Controller 类。可能将您的方法注释更改为例如@GetMapping(path = "/get",produces = APPLICATION_XML_VALUE) 可以解决问题。
-
@Gewure 不,不管你把它放在哪里(类或方法级别),尝试检查代码github.com/maslick/fluxish 并自己玩。
标签: java xml spring-boot spring-webflux jackson-dataformat-xml