7 Apr 2016

Retrofit 2.0 Android | Web service using Retrofit.

Retrofit is developed by Square, Inc. It is one of the most popular HTTP Client Library for Android as a result of its simplicity and its great performance compare to the others.

A part from development,Old method to using web service which is quite lengthy and time consuming.

Here retrofit set everything for you automatically. Now Lets implement Retrofit in our code.

Step 1 : Create studio project.
Now we will Add Retrofit library to our project : Visit Retrofit Official Site
For Android Studio you just need to paste below line of code under dependency of  build.gradle file.

compile 'com.squareup.retrofit2:retrofit:2.0.1'

Now, Add Another library called Okhttp to our project
compile 'com.squareup.okhttp:okhttp:2.4.0' 

Now, Add two more Library Gson and GsonConverter to build.gradle
compile 'com.google.code.gson:gson:1.7.2' 
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

Now, Add one more lib to display log of request and response from retrofit.
compile 'com.squareup.okhttp:logging-interceptor:2.6.0'

SERVICE : 
Let's take Login service to implement using retrofit. below is the service for user login which have two parameter Username and password.
http://xyz/service/userlogin?Username=xyz&password=abc

Step 2: Create POJO/Class
Now we will make all POJO of JSON data coming from server. in my case here is the JSON response of the server.
{"status":"true","message":"Login successfully","data":{"id":1,"first_name":"Hasmukh","last_name":"Bhadani"}}

POJO class in Retrofit by Most Easiest Way :

  • Visit pojo.sodhanalibrary - This is Official website to Convert JSON Data into POJO class. Just You have to Copy Paste all the Codes. Rename pojo as per your requirement.


Here I am creating Three POJO : (1)BaseResponse (2)LoginResponse. (3)UserInfo

BaseResponse :
It contain common filed which is used for whole server in the project.

  public class BaseResponse {

    private String message;

    private String status;

    public String getMessage ()
    {
        return message;
    }

    public void setMessage (String message)
    {
        this.message = message;
    }

    public boolean getStatus ()
    {
        return status.equalsIgnoreCase("true");
    }

    public void setStatus (boolean status)
    {
        this.status = String.valueOf(status);
    }
}
LoginResponse :
   public class LoginResponse extends BaseResponse
{
    private Data data;
    public Data getData ()
    {
        return data;
    }
    public void setData (Data data)
    {
        this.data = data;
    }
   
}
UserInfo: 
   public class UserInfo
{
     private String id;

    private String first_name;

    private String last_name;

    public String getId ()
    {
        return id;
    }

    public void setId (String id)
    {
        this.id = id;
    }

    public String getFirst_name ()
    {
        return first_name;
    }

    public void setFirst_name (String first_name)
    {
        this.first_name = first_name;
    }

    public String getLast_name ()
    {
        return last_name;
    }

    public void setLast_name (String last_name)
    {
        this.last_name = last_name;
    }
   
}
Step 3: Create RestClient.java
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.logging.HttpLoggingInterceptor;
import com.truckforload.app.AppUrls;
import java.util.concurrent.TimeUnit;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;

public class RestClient
{
    private static ApiInterface restClient;
    static
    {
        setupRestClient();
    }
    private RestClient() {}

    public static ApiInterface get()
    {
        return restClient;
    }
    private static void setupRestClient()
    {
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(10, TimeUnit.SECONDS);

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);

        HttpLoggingInterceptor interceptorBody = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        client.interceptors().add(interceptor);
        client.interceptors().add(interceptorBody);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppUrls.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        restClient = retrofit.create(ApiInterface.class);
    }
}
Step 4: Create ApiInterface.java
Now create an Interface for all http methods and parameter.

import retrofit.Call;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Query;

public interface ApiInterface
{
    // Login
    @GET("service/userlogin")
    Call<LoginResponse> login( @Query("Username") String strUsername, @Query("password") String strpassword);

}
Step 5: Create AppWs.java
It contain all method of project which are used for service.And it will provide response using call back listener.

import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;

public class AppWs
{
    private static final String TAG = "AppWs";

    public static String login( final LoginRequest request, final Context context, final WsListener listener )
    {
        String unm= request.getUsername();
        String password = request.getPassword();

        Call<LoginResponse> call = RestClient.get().login(unm, password);
        try
        {
            call.enqueue(new Callback<LoginResponse>()
            {
                @Override
                public void onResponse( Response<LoginResponse> response, Retrofit retrofit )
                {
                    LoginResponse baseResponse = response.body();
                    if ( baseResponse != null && response.isSuccess() )
                    {
                        if ( listener != null )
                        {
                            listener.onResponseSuccess(baseResponse);
                        }
                    }
                    else
                    {
                        if ( listener != null )
                        {
                            ResponseBody errorBody = response.errorBody();

                            if ( errorBody != null )
                            {
                                listener.notifyResponseFailed(errorBody.toString(), null);
                            }
                        }

                    }
                }

                @Override
                public void onFailure( Throwable t )
                {
                    retrofitError(t, listener, context);
                }

            });

        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
        return "";
    }


    public static void retrofitError( Throwable t, WsListener listener, Context context )
    {
        if ( listener != null )
        {
            t.printStackTrace();
            listener.notifyResponseFailed(null, null);
        }
    }

    public interface WsListener
    {
        void onResponseSuccess( BaseResponse baseResponse );

        void notifyResponseFailed( String message, BaseRequest request );
    }
}
Step 6: Create MainActivity.java
Below is the Method which is call on SignIn Button in the activity

private void callServiceLogin()
    {
  ProgressDialog progressDialog = new ProgressDialog(this);
  progressDialog.setMessage("Loading...");
  progressDialog.setCancelable(false);

        LoginRequest loginRequest = new LoginRequest();

        String phone = etUserName.getText().toString();
        loginRequest.setUsername(phone);

        String password = etPassword.getText().toString();
        loginRequest.setPassword(password);

        AppWs.login(loginRequest, this, new AppWs.WsListener()
        {
            @Override
            public void onResponseSuccess( BaseResponse baseResponse )
            {
  if (progressDialog != null && progressDialog.isShowing())
             {
                 progressDialog.dismiss();
             }

                if ( baseResponse instanceof LoginResponse )
                {
                    LoginResponse loginResponse = (LoginResponse) baseResponse;

                    boolean status = loginResponse.getStatus();
                    UserInfo userInfo = loginResponse.getData();
                }
            }

            @Override
            public void notifyResponseFailed( String message, BaseRequest request )
            {
                dismissProgressDialog();                
            }
        });

    }
Here is the official site to get more API interface declaration for service. Visit here.

Find following are the reference links to go in deep for retrofi 2.0 :
https://guides.codepath.com/android/Consuming-APIs-with-Retrofit
http://www.iayon.com/consuming-rest-api-with-retrofit-2-0-in-android/

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

12 comments:

  1. Thank you very much for this tutorial. I would only suggest if you can give more details regarding each code and what it does.
    Thank you again.

    ReplyDelete
  2. Thank you very much for this tutorial. I would only suggest if you can give more details regarding each code and what it does.
    Thank you again.

    ReplyDelete
  3. In the LoginResponse class shouldn't the Field type be UserInfo instead of Data ?

    ReplyDelete
  4. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs Training in online

    ReplyDelete
  5. You’ve written a really great article here. Your writing style makes this material easy to understand.. I agree with some of the many points you have made. Thank you for this is real thought-provoking content
    python training Course in chennai | python training in Bangalore | Python training institute in kalyan nagar

    ReplyDelete
  6. I would really like to read some personal experiences like the way, you've explained through the above article. I'm glad for your achievements and would probably like to see much more in the near future. Thanks for share.

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete