Posted In: Spring, Spring REST

Spring Asynch Rest Client – Using Apache HTTPComonents library example1

Usecase

Application needs to use Apache HTTP Component library to call REST services. Spring provides HttpComponents factory to do that. By default Spring will use default JDK capabilities to call REST services.

Maven entry for httpasyncclient

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpasyncclient</artifactId>
	<version>4.1.3</version>
</dependency>

 

package com.example;

import java.net.URI;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.AsyncClientHttpRequest;
import org.springframework.http.client.AsyncClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsAsyncClientHttpRequestFactory;
import org.springframework.util.concurrent.ListenableFuture;

public class AsyncRestTmpltHttpComponent {
	public static void main(String[] args) {
		new AsyncRestTmpltHttpComponent().proceed();
	}

	public void proceed() {
		System.out.println(
		        "AsyncRestTmpltHttpComponent::proceed() started");
		try {
			AsyncClientHttpRequestFactory acrf = new HttpComponentsAsyncClientHttpRequestFactory();
			URI uri = new URI(
			        "http://localhost:8080/Example201726/time/30");
			AsyncClientHttpRequest asynReq = acrf
			        .createAsyncRequest(uri, HttpMethod.GET);
			ListenableFuture<ClientHttpResponse> future = asynReq
			        .executeAsync();
			ClientHttpResponse response = future.get();

			System.out.println(
			        IOUtils.toString(response.getBody()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(
		        "AsyncRestTmpltHttpComponent::proceed() ends");
	}
}

by , on July 23rd, 2017

  • Categories