Spring MVC - HTTP Streaming using ResponseBodyEmitter

[Updated: Jan 3, 2017, Created: Jan 3, 2017]

A handler method which returns ResponseBodyEmitter can be used for HTTP Streaming.

ResponseBodyEmitter can send multiple Objects to the client, where each Object sent is written to the response with an HttpMessageConverter.

Let's see an example how to achieve that.

The controller

public class MyWebController {

  public ResponseBodyEmitter handleRequest () {

      final ResponseBodyEmitter emitter = new ResponseBodyEmitter();
      ExecutorService service = Executors.newSingleThreadExecutor();
      service.execute(() -> {
          for (int i = 0; i < 1000; i++) {
              try {
                  emitter.send(i + " - ", MediaType.TEXT_PLAIN);

              } catch (Exception e) {

      return emitter;

Spring boot main class

public class HttpStreamingExample {
    public static void main (String[] args) {
        SpringApplication.run(HttpStreamingExample.class, args);

Accessing in browser:

Wrapping ResponseBodyEmitter in ResponseEntity

The handler method can also return ResponseEntity with ResponseBodyEmitter wrapped as the body. We would probably want to do that to customize the status and headers of the response. Please look at our MyWebController3.java in the example project below.

Example Project

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

Http Streaming Examples Select All Download
  • spring-mvc-http-streaming
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also

Spring boot tutorials