
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface UserResource { | |
@GET("user/list") | |
Call listAll(); | |
} |
Step 2 – Retrofit Instance
So, we gonna need a Retrofit instance to call this UserResource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
UserResource userResource = retrofit.create(UserResource.class) |
Easy, isn’t it?
Step 4 – Call
Let’s execute UserResource method listAll() synchronously:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!