【发布时间】:2018-11-28 22:44:09
【问题描述】:
我无法使用 webClient (webflux) 有效使用 pdf rest web 服务
这是我的 webClient 创建:
ExchangeStrategies pdfExchangeStrategy = ExchangeStrategies
.builder()
.codecs(
clientCodecConfigurer -> {
CustomCodecs customCodecs = clientCodecConfigurer.customCodecs();
final ByteArrayDecoder byteArrayDecoder = new ByteArrayDecoder(){
@Override
public List<MimeType> getDecodableMimeTypes() {
return Collections.singletonList(APPLICATION_PDF);
}
};
customCodecs.decoder(byteArrayDecoder);
customCodecs.encoder(new ByteArrayEncoder());
DecoderHttpMessageReader pdfReader = new DecoderHttpMessageReader(byteArrayDecoder);
customCodecs.reader(pdfReader);
}
)
.build();
this.webClient = webClientFactory
.newBuilder(logger, "My web client")
.exchangeStrategies(pdfExchangeStrategy)
.defaultHeader(ACCEPT, APPLICATION_PDF_VALUE)
.defaultHeader(CONTENT_TYPE, APPLICATION_PDF_VALUE)
.baseUrl(this.baseUrl)
.build();
这是我的电话:
webClient.get()
.uri("http://localhost:8084/my-app/document/{id}", id)
.accept(APPLICATION_PDF)
.retrieve()
.bodyToMono(Byte[].class)
.block();
我得到这个错误:
org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/pdf' not supported
即使在supportedMediaTypes 中,我也有application/pdf
使用的网络服务是:
@GetMapping(value = "/document/{id}", produces = APPLICATION_PDF_VALUE)
public ResponseEntity<byte[]> getDocument(@PathVariable String id) throws IOException {
LOGGER.info("get document with id = {}", id);
byte[] pdf = getInvoicePdf("document/sample.pdf");
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("filename", id + ".pdf");
headers.setContentType(APPLICATION_PDF);
headers.setContentLength(pdf.length);
return ResponseEntity
.ok()
.headers(headers)
.body(pdf);
}
感谢您的帮助
【问题讨论】:
-
只需将我的调用更改为如下,它就可以工作: webClient.get() .uri("localhost:8084/my-app/document{id}", id) .accept(APPLICATION_PDF) .exchange() .doOnSuccess (errorConsumer) .block() .bodyToMono(byte[].class) .block();
标签: java spring-boot spring-webflux