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 “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 createService(Class 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 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 } }); 

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

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