AsyncTasks
, work is done in a background thread, and upon completion it returns the result to the main UI thread.
To use Retrofit, declare a service using a simple interface with annotated methods. Then, use the Retrofit
class to create an object which can be used for REST calls. When Retrofit returns the result of the network call to the main UI thread, it can be parsed from JSON to Java domain objects by using a converter such as the GsonConverter
. The use of this converter requires getters and setters with the same name as the JSON object keys.
As Retrofit handles the communication between the main UI thread and a background thread, in addition to JSON parsing when using a converter, it can greatly simply the workflow by reducing the amount of overhead.
Below is an example of the MessageService.java
interface.
public interface MessageService {
@GET("/messages")
Call<List<Message>> listMessages();
@POST("/message")
Call<Message> send(@Body Message message);
}
enqueue()
. This is to run our request asynchronously. If we wanted to run a synchronous request, execute()
could be used instead.
// Retrofit needs to know how to deserialize response, for instance into JSON
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://mobile-course.herokuapp.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
MessageService msgs = retrofit.create(MessageService.class);
msgs.listMessages().enqueue(new Callback<List<Message>>() {
@Override
public void onResponse(Response<List<Message>> response) {
List<Message> messages = messages.response.body();
// Successfull request, do something with the retrieved messages
}
@Override
public void onFailure(Throwable t) {
// Failed request.
}
});
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'