Using Retrofit 2.x as REST client - Tutorial 1

Using Retrofit 2.x as REST client - Tutorial 1

1. Retrofit

1.1. What is Retrofit

Retrofit is a REST Client for Java and Android. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice. In Retrofit you configure which converter is used for the data serialization. Typically for JSON you use GSon, but you can add custom converters to process XML or other protocols. Retrofit uses the OkHttp library for HTTP requests.

Add the following dependencies to your build.gradle file.
// retrofit
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

Create New Java file RetrofitInterface.java

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

/**
 * Interface for Retrofit
 */

public interface RetrofitInterface {


    @POST("user/login")
    @FormUrlEncoded
    Call<PojoUserLogin> login(@Field("countryCode") String countryCode,
                              @Field("userName") String userName,
                              @Field("fullName") String fullName,
                              @Field("birthDate") String birthDate,
                              @Field("profileUrl") String profileUrl,
                              @Field("loginType") String loginType,
                              @Field("deviceInformation") String deviceInformation);
}

Create New Java file Common.java  Application in manifest file.

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.fabric.sdk.android.Fabric;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Common extends Application {

    private Context mContext;
    private static RetrofitInterface mRetrofitInterface;

    @Override
    public void onCreate() {
        super.onCreate();
        Fabric.with(this, new Crashlytics());


        mContext = this;
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

    }


    public static boolean isInternetConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService
                (Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = connectivityManager != null ? connectivityManager
                .getActiveNetworkInfo() : null;
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    public static RetrofitInterface getRetroFitInterface(Context mContext) {
        if (mRetrofitInterface == null) {
            initializeRetrofit(mContext);
        }
        return mRetrofitInterface;
    }

    private static void initializeRetrofit(final Context mContext) {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.readTimeout(Constants.TIMEOUT_SECONDS, TimeUnit.SECONDS);
        builder.connectTimeout(Constants.TIMEOUT_SECONDS, TimeUnit.SECONDS);
        builder.followRedirects(false);

        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(interceptor);
        }
       
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();
                Request request;
             
                    request = original.newBuilder()
                            .header(mContext.getString(R.string.android), mContext.getString(R.string.android))
                            .header(mContext.getString(R.string.apiKey), mContext.getString(R.string.testAppKey))
                            .method(original.method(), original.body())
                            .build();
               
                return chain.proceed(request);
            }
        });

        Retrofit retrofit = new Retrofit.Builder().baseUrl(BuildConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(builder.build()).build();
        mRetrofitInterface = retrofit.create(RetrofitInterface.class);
    }


    public static void setUserData(PojoUserLogin.ResponseData responseData, Context mContext, String mLoginType, String mMobileNumber, String mCountryCode) {

        if (responseData.getPojoSettingModel() != null) {
            new PreferenceDefaultSettings(mContext).setSession(responseData.getPojoSettingModel().getSensitivity(), responseData.getPojoSettingModel().isNotifyCharger() + "",
                    responseData.getPojoSettingModel().isChargerDetection() + "", responseData.getPojoSettingModel().isVibrate() + "",
                    responseData.getPojoSettingModel().isFlash() + "", responseData.getPojoSettingModel().getbAlarmTime(), responseData.getPojoSettingModel().getbDetectionTime(), responseData.getPojoSettingModel().getAlarmTone());
            new PreferenceSettings(mContext).setToneId(responseData.getPojoSettingModel().getAlarmTone());
        }
        
    }

  
}