Retrofit 2.0 — Just a Tip

by Philip Barlow / from beautifuldecay.com

Yes, I’m late to post about Retrofit, but this post is in my drafts box there is a long time! =D It will not be a big post explaining each detail of this framework even because I’m late (again) and there is already lot of posts doing this job . I will try to do something diferente, resuming the use of Retrofit in a easy way to see how it works.

Step 1 – Implement the Resource

Firstly, we must to create a interface that will represent each resources from the API that will be consumed.


public interface UserResource {
@GET("user/list")
Call listAll();
}

Step 2 – Retrofit Instance

So, we gonna need a Retrofit instance to call this UserResource


Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.myapi.com/")
.build(); retrofit = new Retrofit.Builder()
.baseUrl("http://api.myapi.com/")
.build();

Step 3 – Instanciate the Resource

And, we gonna instanciate our UserResource like that:


UserResource userResource = retrofit.create(UserResource.class)

Easy, isn’t it?

Step 4 – Call

Let’s execute UserResource method listAll() synchronously:


Call callUser = userResource.listAll();
Response response = callUser.execute();
Integer HttpResponseCode = response.code(); //202 HTTP_OK
List userList = response.body();

view raw

ListAll.java

hosted with ❤ by GitHub

Or we can do it assynchronously:


Call callUser = userResource.listAll();
call.enqueue(new Callback() {
@Override
public void onResponse(Response response) {
Integer HttpResponseCode = response.code(); //202 HTTP_OK
List userList = response.body();
}
@Override
public void onFailure(Throwable t) {
//Ops! Failed!
}
});

view raw

Callback.java

hosted with ❤ by GitHub

I will post more details soon!

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair /  Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s