How to invoke a REST API Asynchronously
Dependencies:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore-nio</artifactId>
<version>4.3</version>
</dependency>
Sample Code snippet:
private static void sendAsyncRequest(final HttpPost postRequest,
FutureCallback futureCallback, CountDownLatch latch)
throws IOException {
CloseableHttpAsyncClient client;
client = HttpAsyncClients.createDefault();
client.start();
client.execute(postRequest, futureCallback);
try {
latch.await();
} catch (InterruptedException e) {
log.error("Error occurred while calling end point - " + e);
}
}
private void postRequest() throws IOException {
final HttpPost postRequest = new HttpPost("www.google.com");
final CountDownLatch latch = new CountDownLatch(1);
FutureCallback<HttpResponse> futureCallback =
new FutureCallback<HttpResponse>() {
@Override public void completed(final HttpResponse response) {
latch.countDown();
if ((response.getStatusLine().getStatusCode() != 201)) {
log.error("Error occurred while calling end point - " + response.getStatusLine().getStatusCode() +
"; Error - " +
response.getStatusLine().getReasonPhrase());
} else {
if (log.isDebugEnabled()) {
log.debug("Success Request - " + postRequest.getURI().getSchemeSpecificPart());
}
}
}
@Override public void failed(final Exception ex) {
latch.countDown();
log.error("Error occurred while calling end point - "
+ postRequest.getURI().getSchemeSpecificPart() +
"; Error - " + ex);
}
@Override public void cancelled() {
latch.countDown();
log.warn("Operation cancelled while calling end point - " +
postRequest.getURI().getSchemeSpecificPart());
}
};
sendAsyncRequest(postRequest, futureCallback, latch);
}