How to create an asynchronous HTTP call in JAVA

apache

This tutorial explains How to create an asynchronous HTTP call in JAVA.

What is asynchronous HTTP call?

Asynchronous HTTP Request call allows us to process a HTTP call using non-blocking I/O in seperate thread. The main use for Asynchronous HTTP call is where the client is calling a server with a delayed response, which may results in client blocking the server for a long time. So to avoid such type of call we generally prefer to use the Asynchronous HTTP call.

private static boolean makeAsyncCall(final String URL) throws Exception{
	CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
	
	boolean success = false;
	try {
		httpclient.start();
		HttpGet request = new HttpGet(URL);
		Future<HttpResponse> future = httpclient.execute(request, null);
		HttpResponse response = future.get(5,TimeUnit.SECONDS);
		int statusCode = response.getStatusLine().getStatusCode();

		LOGGER.info("responseCode-->"+statusCode+" for mailerURL : "+URL);
		
		if (statusCode == HttpStatus.SC_OK) {
			success = true;
		}
	} catch (Exception e) {
		LOGGER.info("Exception occured ",e);
	}finally {
		httpclient.close();
	} 
	return success;
}

public static void main(String[] args) {
	try {
		makeAsyncCall("http://my-URL");
	} catch (Exception e) {
		e.printStackTrace();
	}
}