我无法使用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
消耗的Web服务是:
@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);
}
感谢您的帮助
答案 0 :(得分:0)
最后不需要所有样板交换策略,解决此问题所需的全部是:
webClient.get()
.uri("http://localhost:8084/my-app/document/{id}", id)
.accept(APPLICATION_PDF)
.exchange()
.block()
.bodyToMono(byte[].class)
.block()