Close

Spring MVC - HTTP Streaming directly to OutputStream

[Last Updated: Jan 4, 2017]

In situations where we want to write raw streaming bytes to the output, our handler method should return an instance of StreamingResponseBody instead of ResponseBodyEmitter.

ResponseBodyEmitter writes output message through HttpMessageConverter, whereas, StreamingResponseBody writes directly to response OutputStream.

StreamingResponseBody is preferable when streaming videos or large files.

StreamingResponseBody is an interface with only one method:

void writeTo(OutputStream outputStream)
      throws IOException

Using this interface is very similar to using Callable for async processing. Spring takes care of thread management, handler method just needs to return an implementation of StreamingResponseBody.

Let's see an example:

The controller

@Controller
public class TestController {

    @RequestMapping("/")
    public StreamingResponseBody handleRequest () {

        return new StreamingResponseBody() {
            @Override
            public void writeTo (OutputStream out) throws IOException {
                for (int i = 0; i < 1000; i++) {
                    out.write((Integer.toString(i) + " - ")
                                        .getBytes());
                    out.flush();
                    try {
                        Thread.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }
}

Spring boot main class

@SpringBootApplication
public class StreamingResponseBodyExample {
    public static void main (String[] args) {
        SpringApplication.run(StreamingResponseBodyExample.class, args);
    }
}

Output


Like ResponseBodyEmitter, StreamingResponseBody can also be used as the body of ResponseEntity, please check out our example TestController2.java in the project browser below.




Example Project

Dependencies and Technologies Used:

  • Spring Boot 1.4.2.RELEASE
    Corresponding Spring Version 4.3.4.RELEASE
  • Spring Boot Web Starter : Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
  • JDK 1.8
  • Maven 3.3.9

Streaming Raw Output Select All Download
  • spring-stream-response-body
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • TestController.java

    See Also