Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send response asynchronously in Spring boot

Need to add following functionality to my Spring Boot based REST application:

When a POST method is called, a long running process is started. At regular intervals (every 5 seconds or so), I need to display a message in the browser to the user, until the process ends.

Note: This method may not be just called from a browser. Might be called in the future from a shell script. The goal is to send response intermittently in the 'response body'.

I tried adding code such as this:

                    OutputStream os = response.getOutputStream();
                    os.write(msg.getBytes());
                    os.flush();

But got NullPointer exception while flushing.

How would I do this? Do I have to make an AJAX call or something like that?

like image 564
DilTeam Avatar asked Aug 02 '26 19:08

DilTeam


1 Answers

There are a couple of problems here. The most fundamental is that HTTP isn't designed to send multiple responses to a single request. Secondly, blocking a request processing thread for the duration of a long-running process is likely to cause problems.

A better approach would be to send a response as soon as the long running process is initiated. This response would have a 202 Accepted status code and a Location header that provides another URI that can be polled by the client to get information about the long-running tasks. For example: Location: https://yourapi.example.com/tasks/123456. It's then the client's responsibility to execute a GET requests against this tasks URI to obtain information about the progress of the long-running process.

like image 160
Andy Wilkinson Avatar answered Aug 04 '26 09:08

Andy Wilkinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!