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.


16 thoughts on Efficient REST request with Spring Android

  1. Pingback: Efficient REST request with Spring Android | Mobile | Syngu

  2. 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

  3. 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!

  4. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>