Searching...
Wednesday, 3 September 2014

Spring 4 AsyncRestTemplate Example

10:43
Spring's central class for asynchronous client-side HTTP access. Exposes similar methods as RestTemplate, but returns ListenableFuture wrappers as opposed to concrete results. See more about AsyncRestTemplate
1. Create a maven project with below dependencies 
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-core</artifactid>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-web</artifactid>
<version>4.0.6.RELEASE</version>
</dependency>
2. Create a main class to test AsyncRestTemplate
import java.util.concurrent.ExecutionException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRestTemplate;

public class AsyncRestTemplateExample {

public static void main(String[] args) {

String url = "http://pretechsol.com";
AsyncRestTemplate asyncRestTemplate = null;
HttpMethod method = null;
try {

// Create AsyncRestTemplate object
asyncRestTemplate = new AsyncRestTemplate();

// Define http method
method = HttpMethod.GET;

// Define response type
Class responseType = String.class;

// Define headers

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);

HttpEntity<String> requestEntity = new HttpEntity<String>("params",
headers);
ListenableFuture<ResponseEntity<String>> future = asyncRestTemplate
.exchange(url, method, requestEntity, responseType);

ResponseEntity<String> entity = future.get();
System.out.println(entity.getBody());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}

}

0 comments: