Streaming HttpOutputMessage Examples



Some examples of using Spring's `Streaming HttpOutputMessage` interface. 

Example 1: Streaming a File

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@RestController
public class FileStreamingController {

    @GetMapping("/download")
    public StreamingResponseBody downloadFile(HttpServletResponse response) throws IOException {
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"example.txt\"");

        File file = new File("path/to/example.txt");
        FileInputStream inputStream = new FileInputStream(file);

        return outputStream -> {
            int nRead;
            byte[] data = new byte[1024];
            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                outputStream.write(data, 0, nRead);
            }
            inputStream.close();
        };
    }
}

Example 2: Streaming JSON Response

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.stream.IntStream;

@RestController
public class JsonStreamingController {

    @GetMapping("/stream")
    public StreamingResponseBody streamJson(HttpServletResponse response) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        return outputStream -> {
            for (int i = 1; i <= 10; i++) {
                String json = "{\"id\": " + i + ", \"name\": \"Item " + i + "\"}\n";
                outputStream.write(json.getBytes());
                outputStream.flush();
                Thread.sleep(1000); // Simulate delay between each item
            }
        };
    }
}

These examples demonstrate how to use `Streaming HttpOutputMessage` to stream a file or a JSON response. In the first example, a file is streamed as a response, while in the second example, a JSON stream is generated and sent as a response.


Post a Comment

Previous Post Next Post