Spring's RestTemplate is a robust, popular Java-based REST client. The Spring Android Rest Template Module provides a version of RestTemplate that works in an Android environment.
Add the spring-android-rest-template artifact to your classpath:
<dependency> <groupId>org.springframework.android</groupId> <artifactId>spring-android-rest-template</artifactId> <version>${org.springframework.android-version}</version> </dependency>
Doing so will transitively include the spring-android-commons-logging module.
At the moment, commons-httpclient 3.x is also required for RestTemplate to work on Android without further customization:
<dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>
In a future release, Spring Android will provide support for Http Client 4, which is used on Android by default.
Using Rest Template, it's easy to invoke RESTful APIs. Below are several usage examples.
The following example shows a query to google for the search term "Thanksgiving".
RestTemplate restTemplate = new RestTemplate(); restTemplate.setRequestFactory(new CommonsClientHttpRequestFactory()); String url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q={query}"; String result = restTemplate.getForObject(url, String.class, "Thanksgiving");
Alternatively, suppose you have defined a Java object you wish to populate from a RESTful web request that returns JSON content.
Define your object based on the JSON data being returned from the RESTful request:
public class Event { private Long id; private String title; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public String setTitle(String title) { this.title = title; } }
Make the RestTemplate request:
RestTemplate restTemplate = new RestTemplate(); restTemplate.setRequestFactory(new CommonsClientHttpRequestFactory()); String url = "https://mypretendservice.com/events"; Event[] events = restTemplate.getForObject(url, Event[].class);