提问者:小点点

Spring WebFlux:使用混合替换HTTP响应的标头流式传输原始HTTP响应字符串


使用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.区间(1000). map(fetchImageFrame)),但我找不到如何流式传输原始HTTP响应数据的方法,大多数示例只允许我访问HTTP主体,但不能访问整个响应,在那里我可以控制HTTP头。


共1个答案

匿名用户

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

像这样的东西:

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