Open top menu


Explain how to used Retrofit in android?

In this tutorial implement  custom classes for Retrofit API Call .

Add dependencies

implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.google.code.gson:gson:2.3.1'



create Class RestCallback.java

 
public abstract class RestCallback<T> implements Callback<T> {
    public static final String UN_SUCCESSFULL =  ContainMsg.UN_SUCCESSFULL;
    public static final String NO_CONNECTION = ContainMsg.Connectio_Error;

    public abstract void restResponse(boolean isSuccess, String message, Object response);

    @Override    public void onFailure(Call<T> call, Throwable t) {
        if (t instanceof SocketException || t instanceof SocketTimeoutException) {
            restResponse(false, UN_SUCCESSFULL, null);
            Log.e("RestCallback", t.getMessage());
        }else {
            restResponse(false, NO_CONNECTION, null);
            Log.e("RestCallback", t.getMessage());
        }
    }


    @Override    public void onResponse(Call<T> call, Response<T> response) {

        if (response.isSuccessful()) {
            try {
                Log.e("Response", new Gson().toJson(response.body()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            restResponse(true, null, response.body());
        }else if (response.code()==401) {
            String str = ContainMsg.InvalidUser;
            restResponse(false, str, null);
        }else {
            restResponse(false,ContainMsg.connectioncoultnotbe, null);
        }
    }


}








 

Create RestClient.Java
public class RestClient { public static String BASE_URL; private static Retrofit retrofit = null; private static RestService apiService = null; public static RestService getClient() { String credentials = App.getString("Username") + ":" + App.getString("Password"); if (retrofit == null) { // create Base64 encodet string final String basic = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(UnsafeOkHttpClient.getUnsafeOkHttpClient(basic)) .build(); apiService = retrofit.create(RestService.class); } return apiService; } public static void restart() { retrofit = null; apiService = null; BASE_URL = GetUrl_whichMode(); } public static String GetUrl_whichMode() { return "http://" +"Your URL" + "/apis/";
    }

}




 

 
 Create Interface
public interface RestService {
    @POST("GetLogin")
    Call doLogin(@Body LoginRequest request);

}




 

 Create OkHttpClient Authencation Class.



public class UnsafeOkHttpClient {



    public static OkHttpClient getUnsafeOkHttpClient(final String basic) {
        try {
            // Create a trust manager that does not validate certificate chains            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // Create an ssl socket factory with our all-trusting manager            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });


            builder.addInterceptor(new Interceptor() {
                @Override                public Response intercept(Chain chain) throws IOException {
                    return chain.proceed(chain.request().newBuilder()
                            .addHeader("Content-Type", "application/json")
                            //.addHeader("Content-Type", "application/json")                            .addHeader("Authorization", basic).build());
                }
            });
            OkHttpClient okHttpClient = builder
                    .readTimeout(120, TimeUnit.SECONDS)
                    .writeTimeout(120, TimeUnit.SECONDS)
                    .connectTimeout(120, TimeUnit.SECONDS)
                    .build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}




Used in Main Activity...


 //Login request ...

public void setLogin(LoginRequest loginRequest) {
    if (isConnectingToInternet(this)) {
        ProgressDialogUtils.showLoader(this);
        App.saveString("Username", loginRequest.getUserName());
        App.saveString("Password", loginRequest.getPassword());
        RestClient.restart();
        RestClient.getClient().doLogin(loginRequest).enqueue(callback);
    }

}






RestCallback callback = new RestCallback() {
    @Override    public void restResponse(boolean isSuccess, String message, Object response) {
        try {
            if (isSuccess) {
                if (response instanceof LoginResponse) {
                  
                }  
            } 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ProgressDialogUtils.hideLoader();
        }
    }
};


Read more