Retrofit :
The retrofit library which is used for converting simple rest api calls to java interfaces. In terms of performance, Retrofit wins over volley and other libraries. Retrofit is developed by Square team. Retrofit takes less time to implement and focus on the rest.
The below are simple steps to start with Retrofit :
Add dependency in build.gradle :
compile ‘com.squareup.retrofit:retrofit:1.9.0’
|
You can see the below example with proper steps to achieve this :
- Create an Interface
- Create a Rest Adapter
- Implementation for interface RestService
- Consume Api calls
public class MyApi {
public static final String BASE_URL = "https://api.github.com"; //1.Create interface // 2.Create rest adapter // 3.Implemention for interface RestService //4.Consume APis //1.Create interface public interface RestService { //synchronous get method, dont run on UI thread. @GET("/users/{user}/repos") List<Repo> listRepos(@Path("user") String user); //Asynchronous get method, can run on UI thread. @GET("/users/{user}/repos") void listReposAsync(@Path("user") String user, Callback<List<Repo>> callback); } // 2.Create rest adapter private RestAdapter buildRestAdapter() { RestAdapter.Builder builder = new RestAdapter.Builder(); builder.setEndpoint(BASE_URL); //displaying logs in logcat with request and response //set NOne in producation builds builder.setLogLevel(RestAdapter.LogLevel.FULL); RestAdapter adapter = builder.build(); adapter.create(RestService.class); return adapter; } //3.Implemention for interface RestService public RestService getRestService() { RestAdapter adapter = buildRestAdapter(); RestService service = adapter.create(RestService.class); return service; } //4.Consume APis - Sync public List<Repo> getRepos(String gitUserName) { return getRestService().listRepos(gitUserName); } //4.Consume APis - Async public void getReposAsync(String gitUserName, Callback<List<Repo>> callback) { getRestService().listReposAsync(gitUserName, callback); } } |
Find the source code in github :