Efficient REST request with Spring Android
In previous articles somebody recommend me to use Spring Android to make REST request more efficiently, so I started to work and thought to write an article to show you all how to do it in a simple way.
For that purpose, we’ll use the previous examples (1,2) but with a simple modification in the JSON format. This time, the JSON object will be returned this way:
[
{"emails":["email.2@yahoo.com","emailnew@gmail.com"],”name”:”Contacto 1″,”numbers”:["78789987","78789227","44449987"]},
{“emails”:["contacto2@gmail.com","contacto3@gmail.com"],”name”:”Contacto 2″,”numbers”:["22449987","29393291"]},
{“emails”:["contacto3@gmail.com","contacto3@gmail.com"],”name”:”Contacto 3″,”numbers”:["2222287","27283931"]}
]
Before, we made the request with the Android clients that come by default, but now we’re going a step futher using Spring Android. The first thing we have to do is to download the corresponding libraries: Spring’s and Jackson’s libraries.
Once the project is ready, the only thing we have to do is use the Spring library with the RestTemplate class:
/**
* Get method for the JSON Contacts
*/
public List<Contact> getContacts() {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
String url = "http://domain/resources/api/json";
MappingJacksonHttpMessageConverter messageConverter = new MappingJacksonHttpMessageConverter();
List<HttpMessageConverter<?>> messageConverters = Lists.newArrayList();
messageConverters.add(messageConverter);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(messageConverters);
ResponseEntity<Contact[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Contact[].class);
Contact[] result= responseEntity.getBody();
return Arrays.asList(result);
}
As we can see, the getContacts() method has changed completely and all has been simplified (if we see this example…. ejemplo). The only thing we have to do is select the request headers we want to use (in this case we’re setting the accept to receive JSON objects), and set the converters we’re using (in this case we’ll use MappingJacksonHttpMessageConverter, althought we could use GsonHttpMessageConverter including the neccesary libraries).
Finally, we’ll use exchange specifying all the parameters to get the entity, and after this the getBody() method to get the Contacts list.
As we can observe, all has been simplified, including the JSON objects parsing. This way,we can delete all the JSON parser classes that we used before.

Your Posted on is broken.
Shows: %A %B %e%q, %Y
Thanks! I’ll try to fix it!
Pingback: Efficient REST request with Spring Android | Mobile | Syngu
El post me pareció muy interesante y útil, has revisado el uso del ORM en Android, quiero combinar librerias de ORM y REST para poder manejar de mejor manera la sincronización de datos locales en dispositivo mobil y los datos externos en la Web
Gracias
Pues no he revisado nada de ORMs, pero sinceramente me haría mucha falta ahora mismo… Quizás podrías probar con ORMLiteque tiene una versión para Android y parece que tiene buena pinta en principio…
Quizás me anime a probarlo hoy y a escribir un artículo =)
Espero que te haya servido de ayuda
Gracias, el articulo es super útil, hoy lo integre con greenDAO, su integración es muy buena, según sus cifras tiene un performance mejor que ORMLite, recomiendo que lo revises, y esta siguiendo el post para conocer tu opinion
Saludos
Me alegro de que te sirviera! Le daré un vistazo a greenDAO a ver que tal =)
Saludos!
Thanks for a marvelous posting! I definitely enjoyed reading it, you happen to be a great author.I will make sure to bookmark your blog and will eventually come back very soon. I want to encourage you to ultimately continue your great job, have a nice weekend!
Thank you for your comment! I’m glad you like it!! =)
I like this blog very much, Its a very nice berth to read and receive information.
Hi,
How can I cancel a request from user’s input? (Like a ‘Cancel’ button)
Nice post btw, thanks!
Hi! sorry for being late! what do you mean with that?
Thanks!
Hello,
that is actually a pretty good question : how can we stop a request that has been launched. Basically, how to stop the HttpConnection of the underlying spring request.
I am looking for a solution for this problem today, and will post here any update…
(to be followed)
Hi
Can you help me?
I want to get a image file from localhost to my android sd card. I’m using wamp and emulator but I don’t know how should I do that with spring for android. I’ve googled befor but I could not find anythig about that.
I could read a json file with spring for android but for image file NO.
He tartado de hacer lo mismo pero no se como añadir (sin usar maven) las librerías de jackson ya que me da error porque no las encuentra.
I’ve said that least 126168 times. SCK was here