Anirudh Jadhav
Anirudh Jadhav

Reputation: 193

How to Cancel a REST api request?

I use REST API based system, in which there are some requests that take long time to complete. I want to give user an option to cancel the request.

Upvotes: 14

Views: 19003

Answers (2)

Friendy
Friendy

Reputation: 519

Firstly you need to use multiple threads because your program will be on hold while it is sending the request so you cannot click on something until it is back from hold.

Create a thread which calls the rest API in background without hanging the overall application and terminate that thread on click of a button.

note for terminating the thread you need to use stop function which is depreciated now because you cannot interrupt the thread or check a Boolean during the process.

       @Deprecated
       public final void stop()

Alternatively, you can use Maximum Time for a HTTP Request call by

    HttpConnectionParams.setConnectionTimeout(httpParams, 30000);

_For all scenario

  1. Make thread pool method

    executorService = Executors.newFixedThreadPool(1);
    
  2. Put your logical method in callable store in future object

    Future<Boolean> futureObjects = executorService.submit(newCallable<Boolean>() { ....call your logical method which you going run in multiple thread....});
    

    3.Gets your results future object

    return (futureObjects != null)
                    ? futureObjects.get(timeout, TimeUnit.SECONDS)
                            : null;
    

    The default waits until getting separate calls response.

4.IN between calling multiple threads requesting user want to stop or break their multiple thread calls then simply check executor is not terminated then terminate immediately

    if (executorService != null && !executorService.isTerminated(){  
        executorService.shutdownNow();
     }

Upvotes: 0

Eric Stein
Eric Stein

Reputation: 13672

First, support

POST /requests

which will return a reference to the status of the request

{
    "id": 1234,
    "self"": "/requests/1234"
    "status": "Running"
}

Then add support for

PUT /requests/1234
{
    "status": "Canceled:"
}

That will let clients cancel a request if it hasn't finished yet. If the request is to create some other kind of resource, then instead of POST /requests, do POST /myResource, but still return the status object with the pointer to /requests in the response.

Clients can then poll /requests to see when the request is complete.

Upvotes: 6

Related Questions