Spring WebFlux:流原始HTTP响应字符串,带有用于混合替换HTTP响应的标头

时间:2019-02-04 10:46:17

标签: spring-webflux

使用Spring WebFlux,我想返回看起来像这样的混合替换HTTP响应:

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]

从Flux流式传输数据(想想Flux.interval(1000).map(fetchImageFrame)),但是我找不到一种方法来流式传输原始HTTP响应数据,大多数示例仅使我可以访问HTTP正文,但不能访问整个响应我可以在其中控制HTTP标头。

1 个答案:

答案 0 :(得分:1)

您是否尝试过将Flux响应包装在ResponseEntity中并在ResponseEntity上设置所需的标题?

类似的东西:

@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);
    }
}