Basic Retrofit with Authentication | Goodpixelpro Tutorial

Goodpixelpro Tutorial – Pada postingan kali ini penulis ingin memberikan contoh basic template penggunaan Retrofit 2 dengan Authentication. Pertama buat class “” 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 =; return chain.proceed(request); } } 

lalu buat sebuah class konfgurasi Retrofit bernama “” untuk menerima parameter token Auth, seperti dibawah

 public class ApiClient { private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); private static final String BASE_URL = ""; public static  S createService(Class serviceClass, final String authToken) { Retrofit.Builder builder = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()); Retrofit retrofit; if (!TextUtils.isEmpty(authToken)) { AuthenticationInterceptor interceptor = new AuthenticationInterceptor(authToken); if (!httpClient.interceptors().contains(interceptor)) { httpClient.addInterceptor(interceptor); builder.client(; retrofit =; } } return retrofit.create(serviceClass); } } 

lalu buat class interface untuk request method bernama “” contoh:

 public interface ApiService { @GET("/api/v1/secure/get_list_something") Call 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 call = apiService.getSomething(); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { //do something } @Override public void onFailure(Call call, Throwable t) { //do something } }); 


Terimakasih telah berkunjung ke website Goodpixelpro. Semoga bermanfaat.!

There are no comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Start typing and press Enter to search

Shopping Cart