Reputation: 2661
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?
Upvotes: 3
Views: 3649
Reputation: 116231
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.
Upvotes: 8