0

Can't figure out how to obtain response body and send back to client properly. It has an empty body on first execution and works thereafter. Looks like am not handling the async nature of subscribe properly.

Have a controller and service as follows:

ResponseEntity<StreamingResponseBody> responseEntity = null;

@GetMapping(value = "/getPdf", produces = MediaType.APPLICATION_PDF_VALUE)
public ResponseEntity<StreamingResponseBody> getDoc(...

responseEntity = docervice.getByDocIdResponseEntity(userName, docIdTst);

Service is:

public ResponseEntity<StreamingResponseBody> getByDocIdResponseEntity(String userName, String docId) {
this.webClient
    .get()
    .uri(uriBuilder -> uriBuilder.path(this.getByDocIdBaseURL)
        .queryParam("user", userName).queryParam("docId", docId)
        .build())
    .retrieve()       
    .toEntity(byte[].class)
    .subscribe(doc -> {
        log.info("getContentLength: " + doc.getHeaders().getContentLength());
        log.info("content type: " + doc.getHeaders().getContentType().getType() + "/" + doc.getHeaders().getContentType().getSubtype());

        // Extract filename
        String disposition = doc.getHeaders().getFirst("Content-Disposition");
        String filename = null;
        if (disposition != null) {
            int fileSplit = disposition.indexOf("=");
            if (fileSplit > 0) {
                filename = disposition.substring(fileSplit + 1);
                log.debug("filename: " + filename);
            }
        }

        InputStream targetStream = new ByteArrayInputStream(doc.getBody());

        // stream the response by writing to OutputStream
        StreamingResponseBody responseBody = outputStream -> {
            int nRead;
            byte[] data = new byte[config.getDefaultBufferSize()];
            while ((nRead = targetStream.read(data, 0, data.length)) != -1) {
                outputStream.write(data, 0, nRead);
            }
        };

        // response to client
        docIdResponseEntity = ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + filename)
            .contentType(MediaType.APPLICATION_PDF).body(responseBody);
    });

return docIdResponseEntity;
}

How do I handle the async response and send back the ResponseEntity to consumer once ready? Am reading the docs but can't see how to do it.

user1746582
  • 559
  • 1
  • 8
  • 19

0 Answers0