
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(); |
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! | |
| } | |
| }); |
I will post more details soon!