How can we make asynchronous REST api call in Java?

user10937286 :

I am using Spring RestTemplate and want to make a call to another service that doesn't return any response body. So, I don't want to wait for the response. So, it's just fire and forget, and continue with the remaining code. I am thinking of creating a new Thread to do this but really not sure what's the correct approach.

Gal Naor :

The correct approach is to execute the async with a callback (using DeferredResult, like this (assuming we have a class someClass that we want to retrieve from the API:

@GetMapping(path = "/testingAsync")
public DeferredResult<String> value() throws ExecutionException, InterruptedException, TimeoutException {
   AsyncRestTemplate restTemplate = new AsyncRestTemplate();
   String baseUrl = "http://someUrl/blabla";
   HttpHeaders requestHeaders = new HttpHeaders();
   requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
   String value = "";

   HttpEntity entity = new HttpEntity("parameters", requestHeaders);
   final DeferredResult<String> result = new DeferredResult<>();
   ListenableFuture<ResponseEntity<someClass>> futureEntity = restTemplate.getForEntity(baseUrl, someClass.class);

   futureEntity.addCallback(new ListenableFutureCallback<ResponseEntity<someClass>>() {
      @Override
      public void onSuccess(ResponseEntity<someClass> result) {
         System.out.println(result.getBody().getName());
         result.setResult(result.getBody().getName());
      }

      @Override
      public void onFailure(Throwable ex) {
         result.setErrorResult(ex.getMessage());
      }
  });

  return result;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328285&siteId=1
Recommended