0

I have a GET request in my API that can be called via url. My problem is that this request is waiting for some return, even though it may take indefinitely. I would like to return a 200 status code right at the beginning of the application so that the user does not have his page blocked waiting for a response, while the rest of the code is executed normally.

My actual code look like this:

@Controller
public class APITest {

    @RequestMapping(value="test", method=RequestMethod.GET)
        public void RequestTest(
                @RequestParam(value="token", required=false) String token, 
                HttpServletRequest request, HttpServletResponse response)
                throws InterruptedException, ParseException, IOException, SQLException {

            // SOME CODE HERE

            return;
        }   
}

Is what I need possible using this method?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
pnda
  • 23
  • 4
  • How about using `@Async` methods? See this [Getting Started](https://spring.io/guides/gs/async-method/) article. – wjans May 27 '20 at 08:31
  • This remembers me an old [post of mine](https://stackoverflow.com/a/25402616/3545273). You should try to set the status and close the output stream of the response. – Serge Ballesta May 27 '20 at 08:36
  • Thank you @SergeBallesta this worked fine for me! Exactly what I need. Despite the answer from Stephan worked as well, your method is simpler. Thank you! – pnda May 27 '20 at 08:58

1 Answers1

0

You could run the code in a different thread.

@Controller
public class APITest {

    @RequestMapping(value="test", method=RequestMethod.GET)
        public void RequestTest(
                @RequestParam(value="token", required=false) String token, 
                HttpServletRequest request, HttpServletResponse response)
                throws InterruptedException, ParseException, IOException, SQLException {

            CompletableFuture.runAsync(() -> longRunningTask());

            return;
        }   
}

The longRunningTask() will be executed in a different thread and RequestTest() will return directly with a 200.

Stephan Stahlmann
  • 441
  • 2
  • 5
  • 19