Posted In: Spring, Spring REST

Spring Asynch Rest Client – Using Apache HTTPComonents library example2

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 org.springframework.http.ResponseEntity;
import org.springframework.http.client.AsyncClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsAsyncClientHttpRequestFactory;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRestTemplate;

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

	public void proceed() {
		System.out.println(
		        "AsyncRestTmpltHttpComponent2::proceed() started");
		try {
			AsyncClientHttpRequestFactory acrf = new HttpComponentsAsyncClientHttpRequestFactory();
			AsyncRestTemplate art = new AsyncRestTemplate(acrf);
			ListenableFuture<ResponseEntity<String>> lf1 = art
			        .getForEntity(
			                "http://localhost:8080/Example201726/time/30",
			                String.class);
			ResponseEntity<String> entity1 = lf1.get();
			System.out.println(entity1.getBody());
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(
		        "AsyncRestTmpltHttpComponent2::proceed() ends");
	}
}

Tags:

by , on July 24th, 2017

  • Categories