简体   繁体   中英

How to async write HttpHeader to ClientHttpResponse?

I'm creating a webservice that should offer a file for download. The file itself is requested from another external webservice under the hood. So my webservice is more like proxy.

As files could be big, instead of fetching them completely, I'm writing the file directly out as stream.

Problem: the external webservice provides HttpHeaders like Content-Length , Content-Type , Content-Disposition that I would like to forward through my proxy servlet. But as I stream the resource only, the headers are not known at this stage.

@GetMapping(value = "/files/{filename}")
public ResponseEntity<StreamingResponseBody> getDocument(@PathVariable String filename) {
    StreamingResponseBody responseBody = outputStream -> {
        HttpHeaders headers = download(outputStream, filename);
        outputStream.close();
        System.out.println(headers); //always 'null' at this stage
    };

    return ResponseEntity.ok(responseBody); //TODO how to get the header in?
}

private HttpHeaders download(OutputStream outputStream, String filename) {
        ResponseExtractor<HttpHeaders> responseExtractor = clientHttpResponse -> {
            //directly stream the remote file into the servlet response
            InputStream inputStream = clientHttpResponse.getBody();
            StreamUtils.copy(inputStream, outputStream);

            HttpHeaders headers = clientHttpResponse.getHeaders();
            System.out.println(headers); //external headers are shown correctly

            //is it possible to write the headers into the servlet response at this stage??
            return headers;
        };

        return restTemplate.execute("https://www.external-webservice.com?file=" + filename, HttpMethod.GET, null, responseExtractor);
    }

As you see: the headers of the external file are available at ResponseExtractor stage. But when I return those headers into StreamingResponseBody stage, the headers are null .

Question: is it possible at all to get the remote HttpHeaders in case of direct streaming?

The HttpHeaders must be written directly into the HttpServletResponse , before writing the body stream:

private HttpHeaders download(OutputStream outputStream, HttpServletResponse response, String filename) {
    ResponseExtractor<Void> responseExtractor = clientHttpResponse -> {
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, clientHttpResponse.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION));

        InputStream inputStream = clientHttpResponse.getBody();
        StreamUtils.copy(inputStream, outputStream);
        return null;
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM