Sunday, March 18, 2018

Basic Retrofit with Authentication

Pada postingan kali ini penulis ingin memberikan contoh basic template penggunaan Retrofit 2 dengan Authentication. Pertama buat class "AuthenticationInterceptor.java" untuk menambahkan header Authorization yang berisi token Auth, seperti ini
 public class AuthenticationInterceptor implements Interceptor{  
   private String authToken;  
   AuthenticationInterceptor(String token) {  
     this.authToken = token;  
   }  
   @Override  
   public Response intercept(@NonNull Chain chain) throws IOException {  
     Request original = chain.request();  
     Request.Builder builder = original.newBuilder()  
         .header("Authorization", authToken);  
     Request request = builder.build();  
     return chain.proceed(request);  
   }  
 }  


lalu buat sebuah class konfgurasi Retrofit bernama "ApiClient.java" untuk menerima parameter token Auth, seperti dibawah

 public class ApiClient {

   private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
   private static final String BASE_URL = "https://youurl.com";

   public static <S> S createService(Class<S> serviceClass, final String authToken) {
     Retrofit.Builder builder =
     new Retrofit.Builder()
         .baseUrl(BASE_URL)
         .addConverterFactory(GsonConverterFactory.create());

     Retrofit retrofit =builder.build();

     if (!TextUtils.isEmpty(authToken)) {
       AuthenticationInterceptor interceptor =
           new AuthenticationInterceptor(authToken);

       if (!httpClient.interceptors().contains(interceptor)) {
         httpClient.addInterceptor(interceptor);
         builder.client(httpClient.build());
         retrofit = builder.build();
       }
     }
     return retrofit.create(serviceClass);
   }
 }



lalu buat class interface untuk request method bernama "ApiService.java" contoh:
 public interface ApiService {
   @GET("/api/v1/secure/get_list_something")
   Call<BaseResponseModel> getSomething();
 }


lalu panggil request method sesuai kebutuhan dan pass token Auth pada parameter ApiClient.createService, seperti ini
 private String MY_TOKEN = "this is token";

 ApiService apiService = ApiClient.createService(APIService.class, MY_TOKEN);

 Call<BaseResponseModel> call = apiService.getSomething();
 call.enqueue(new Callback<BaseResponseModel>() {
       @Override
       public void onResponse(Call<BaseResponseModel> call,
            Response<BaseResponseModel> response) {
         //do something
       }
 
       @Override
       public void onFailure(Call<BaseResponseModel> call, Throwable t) {
         //do something
       }
     });

Referensi:
https://futurestud.io/tutorials/android-basic-authentication-with-retrofit

No comments:

Post a Comment