Artem Yarulin
Artem Yarulin

Reputation: 285

Spring WebFlux: Stream raw HTTP response string with headers for Mixed-Replace HTTP Response

Using Spring WebFlux I would like to return Mixed-Replace HTTP Response that looks something like this:

HTTP/1.1 200 Ok
Content-Type: multipart/x-mixed-replace; boundary=--icecream

--icecream
Content-Type: image/jpeg
Content-Length: [length]

[data]

--icecream
Content-Type: image/jpeg
Content-Length: [length]

[data]

where data is streamed from Flux (think Flux.interval(1000).map(fetchImageFrame)), but I can't find a way how to stream raw HTTP response data, most of the examples gives me access to HTTP body only, but not whole response where I can control HTTP headers.

Upvotes: 2

Views: 1326

Answers (1)

athom
athom

Reputation: 1608

Have you tried wrapping your Flux response in a ResponseEntity and setting the required headers on the ResponseEntity?

Something like:

@GetMapping(value = "/stream")
ResponseEntity<Flux<byte[]>> streamObjects() {
    Flux<byte[]> flux = Flux.fromStream(fetchImageFrame()).delayElements(Duration.ofSeconds(5));
    HttpHeaders headers = HttpHeaders.writableHttpHeaders(HttpHeaders.EMPTY);
    headers.add("Content-Type", "multipart/x-mixed-replace; boundary=--icecream");
    return new ResponseEntity<>(flux, headers, HttpStatus.OK);
}

private Stream<byte[]> fetchImageFrame() {
    return List.of(
            load("image1.jpg"),
            load("image2.jpg"),
            load("image3.jpg"),
            load("image4.jpg")
    ).stream();
}

private byte[] load(String name) {
    try {
        byte[] raw = Files.readAllBytes(Paths.get(name));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        String headers =
                "--icecream\r\n" +
                "Content-Type: image/jpeg\r\n" +
                "Content-Length: " + raw.length + "\r\n\r\n";
        bos.write(headers.getBytes());
        bos.write(raw);
        return bos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Upvotes: 1

Related Questions